How to serialize c# object array into json object without an array - serialization

I want to use JsonConvert.Serialize in order to serialize a c# array class object into a json non-array object.
public list<employee> employees;
Output:
"{\"employees\":
{\"name\":\"Alex\",\"number\":\"25860340\"},
{\"name\":\"Tom\",\"number\":\"94085345\"}
}"

The format you have asked for in your question would not be valid JSON, because objects are not allowed to follow one another directly unless they are part of an array (see JSON.org). However, you could transform your employee list into a dictionary and serialize that instead, so long as you had a suitable key to use. One idea would be to use the employee number as a key, for example:
var employees = new List<Employee>
{
new Employee { name = "Alex", number = "25860340" },
new Employee { name = "Tom", number = "94085345" }
};
var obj = new
{
employees = employees.ToDictionary(e => e.number)
};
string json = JsonConvert.SerializeObject(obj, Formatting.Indented);
Console.WriteLine(json);
That would give you this output, which is close to what you wanted:
{
"employees": {
"25860340": {
"name": "Alex",
"number": "25860340"
},
"94085345": {
"name": "Tom",
"number": "94085345"
}
}
}
If the employee number isn't actually unique, you could instead use each employee's position in the list as a key like this:
int i = 0;
var obj = new
{
employees = employees.ToDictionary(e => i++)
};
This would give you the following output instead:
{
"employees": {
"0": {
"name": "Alex",
"number": "25860340"
},
"1": {
"name": "Tom",
"number": "94085345"
}
}
}

Related

How to fetch the particular field value from response body

This is the response body of post method
"body":
{
"id": 538,
"Fname": "abc",
"Lname": "Xyz",
"Type": {
"Type": "tryrtyr",
"createdBy": "ytyryr",
"createdDate": "2022-07-22T09:24:37.616+00:00",
"lastModifiedBy": "rtyryry",
"lastModifiedDate": "2022-07-22T09:24:37.616+00:00"
}
}
I tried to fetch the Id value but it is showing null value.
Fname, Lname are passing from excel file.
String jsonString = response.asString();
jsonString = response.asString();
List<Map<String, Object>> body = JsonPath.from(jsonString).get("");
Object Id = null;
for (Map<String, Object> item: body) {
if (item.get("Fname").toString().equals(Fname) &&
item.get("Lname").toString().equals(Lname)); {
Id = Integer.parseInt(item.get("id").toString());
}
}
System.out.println(Id);
Since the body is json object, not array, so you don't need a List here. I think you just need.
int id = response.jsonpath().getInt("id");

how to select value if key is uuid in mongodb

the mongodb data like this:
{
"_id": "123dsadasfa454sdsaw",
"hashmap": {
"uuid-12sadsadw5": {
"name": "bob"
},
"uuid-12sadsadwew5": {
"name": "alice"
}
},
"age": 10
}
"hashmap" like java HashMap, the key is uuid like "uuid-12sadsadwew5" and the value is object.
I want to get the data which the name in "hashmap" value is not null. And I use sql :
db.tabl1.find({"hashmap.values.name":{$ne:null}})
but cannot get the right result
You can use this aggregation query:
First use $objectToArray to create an array with values k and v. As we don't know the key (k) we can search by value (v).
Then $unwind array
And $match values where name is not null.
And then regroup and recreate the object using $arrayToObject.
db.collection.aggregate([
{
"$set": {
"hashmap": {
"$objectToArray": "$hashmap"
}
}
},
{
"$unwind": "$hashmap"
},
{
"$match": {
"hashmap.v.name": {
"$ne": null
}
}
},
{
"$group": {
"_id": "$_id",
"hashmap": {
"$push": "$hashmap"
}
}
},
{
"$set": {
"hashmap": {
"$arrayToObject": "$hashmap"
}
}
}
])
Example here

Need to retrieve the json key value as null if key not present at the node

{
"a": {
"b": 1,
"c": 0
},
"values": [
{
"d": "WERTY",
"e": "details",
"f": [
{
"addressId": "vvvv",
"address": "ffff"
}
]
},
{
"d": "ZXCVB",
"e": "details"
},
{
"d": "ASDFG",
"e": "details",
"f": [
{
"addressId": "vvvv",
"address": "xxxx"
}
]
}
]
}
After getting the response from restassured, I am trying to fetch the values of a particular key with JsonPath.
I am using:
responseBody.jsonPath().getList("values.f.address)
This is returning me a list - ["ffff","xxxx"]
I want to get - ["ffff",null,"xxxx"]
Is it possible to achieve this with Karate?
JsonPath = values[0].f[0].address
If you are using validatableResonse then you can use:
String res_str = Response.extract().jsonPath().getString("values[0].f[0].address");
The response should be of ValidatableResponse type.
It won't return you null for that absent item, because field address is actually not present in the response body.
You can do it checking whether the f key is available in each object of values array;
If it is available -> add the value of address in each object in f array, to a String list
If it is not available -> add null to the same String list.
I create a org.json.JSONObject from io.restassured.response.Response.
Response response = given()
.when()
.get(url)
.then()
.extract()
.response();
List<String> addressList = new ArrayList<>();
JSONObject responseObject = new org.json.JSONObject(response.body().asString());
JSONArray jsonArray = responseObject.getJSONArray("values");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
if (jsonObject.keySet().contains("f")) {
JSONArray fObjectArray = jsonObject.getJSONArray("f");
for (int j = 0; j < fObjectArray.length(); j++) {
addressList.add(fObjectArray.getJSONObject(j).get("address").toString());
}
} else {
addressList.add(null);
}
}
System.out.println(addressList.toString());
This will print the following result;
[ffff, null, xxxx]

Querying nested dictionaries in RavenDB

This question regards querying nested dictionaries.
I have a case which can be simplified into the following setup with a style containing a list of SKUs containing a list of Collis.
CLASS DEFINITIONS:
public class Style
{
public string Name { get; set; }
public Dictionary<string, Sku> Skus = new Dictionary<string, Sku>();
}
public class Sku
{
public string Name { get; set; }
public Dictionary<string, Colli> Collis = new Dictionary<string, Colli>();
}
public class Colli
{
public string Name { get; set; }
}
JSON DATA IN RAVEN DB:
{
"Skus": {
"Sku1": {
"Collis": {
"Right": {
"Name": "Right"
},
"Right again": {
"Name": "Right again"
},
"Wrong": {
"Name": "Wrong"
}
},
"Name": "Sku1"
},
"Sku2": {
"Collis": {
"Wrong 1": {
"Name": "Wrong 1"
},
"Wrong 2": {
"Name": "Wrong 2"
},
"Wrong 3": {
"Name": "Wrong 3"
}
},
"Name": "Sku2"
}
},
"Name": "Style1"
}
VALID QUERIES:
(Ask for style with skus of specific names)
var existingStyleWithSku1 = session.Query<Style>().Where(s => s.Skus["Sku1"] != null).ToList();
var nonexistingStyleWithSku4 = session.Query<Style>().Where(s => s.Skus["Sku4"] != null).ToList();
INVALID NESTED QUERY
(Ask for style containing a sku named "Sku1" that contains a colli named "Right")
var styleWithSpecificColli = session.Query<Style>().Where(s => s.Skus["Sku1"].Collis["Right"] != null).ToList();
When i attempt to execute the last query, I get the message:
{ "Url":
"/indexes/dynamic/Styles?query=-Skus.get_Item(%2522Sku1%2522).Collis.Right%253A%255B%255BNULL_VALUE%255D%255D%2520AND%2520Skus.get_Item(%2522Sku1%2522).Collis.Right%253A*&start=0&pageSize=128&aggregation=None",
"Error": "System.ArgumentException: The field ')CollisRight' is not
indexed, cannot query on fields that are not indexed\r\n at
Raven.Database.Indexing.Index.IndexQueryOperation.AssertQueryDoesNotContainFieldsThatAreNotIndexes()
in c:\Builds\raven\Raven.Database\Indexing\Index.cs:line 628\r\n
at
Raven.Database.Indexing.Index.IndexQueryOperation.d__1c.MoveNext()
in c:\Builds\raven\Raven.Database\Indexing\Index.cs:line 542\r\n
at
System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext()\r\n
at
System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext()\r\n
at System.Collections.Generic.List1.InsertRange(Int32 index,
IEnumerable1 collection)\r\n at
........
Is there a way that I can be able to execute the last query? Maybe defining what to index in RavenDB?
Thankyou in advance.
I posted the example above as failing test, but synhershko corrected my code in order to make it work.
It is actually possible to do this. The query just looks like this instead:
WRONG:
var styleWithSpecificColli = session.Query<Style>()
.Where(s => s.Skus["Sku1"].Collis["Right"] != null)
.ToList();
RIGHT:
var styleWithSpecificColli = session.Query<Style>()
.Select(s => s.Skus["Sku1"])
.Where(c => c.Collis["Right"] != null)
.ToList();

extjs nested json store rails

i am trying to post ext js json store that has some hard coded records..
there is one-to-many relationship between Customer & Product..
{
"customers": [
{
"id": 123,
"name": "Ed",
"products": [
{
"id": 50,
"prodnm": "xyz",
rate:20,
},
{
"id": 60,
"prodnm": "abc",
rate:30,
}
]
}
]
}
iam using rails & want to check whether i m getting proper json response..plz help..
For that you can use this code to get the json from store.
function getJsonOfStore(store){
var datar = new Array();
var jsonDataEncode = "";
var records = store.getRange();
for (var i = 0; i < records.length; i++) {
datar.push(records[i].data);
}
jsonDataEncode = Ext.util.JSON.encode(datar);
return jsonDataEncode;
}
print that json in console then copy that json and past it here, click on format it will show you a formated json.
The best way to check the response is by using Fiddler