So, I am trying to count the amount of values in JSON using c#. The Json is:
{
"Someid": 657442,
"roles": [
{
"id": 3892751,
"name": "Guest",
"rank": 0,
"memberCount": 0
},
{
"id": 3892750,
"name": "Fanz!<3",
"rank": 1,
"memberCount": 0
},
{
"id": 3892749,
"name": "Lead-Singer",
"rank": 254,
"memberCount": 0
},
{
"id": 3892748,
"name": "Drums",
"rank": 255,
"memberCount": 0
}
]
}
I want to count the amount "roles". The JSON is just in a string variable. Help?
You can either use like this:
var token = JToken.Parse(input);
var roles= token.Value<JArray>("roles");
var count = roles.Count;
Or you can also use JsonPath:
var token = JToken.Parse(input);
var count = token.SelectTokens("$.roles[*]").Count();
But ideally, you should be serilizing into an object and then using the properties to get the Count:
public class Role
{
public int id { get; set; }
public string name { get; set; }
public int rank { get; set; }
public int memberCount { get; set; }
}
public class MyObject
{
public int Someid { get; set; }
public List<Role> roles { get; set; }
}
var item = JsonConvert.DeserializeObject<MyObject>(input);
var count = item.roles.Count;
Related
{
"objects": [
{
"id": 123,
"tracking_datas": [
{
"id": 1,
"polygons": [1,3]
},
{
"id": 2,
"polygons": [3]
},
{
"id": 3,
"polygons": [1,2]
}
]
}
]
}
I have a json file as above. And there is a model that satisfies this json in my NetCore project. I want to get objects containing polygonIds that I have determined with the help of mongodb. How can I do this with c# mongo db?
For example, I have a reference array requiredPolygons: [1,2] and I want to get the data containing these polygon'ids in the tracking data of the objects in the json. The expected result is as follows.
{
"objects":
[
{
"id": 123,
"tracking_datas":[
{
"id": 1,
"polygons": [1,3]
},
{
"id": 3,
"polygons": [1,2]
}
]
}
]
}
public class Test
{
public ObjectId Id { get; set; }
public IEnumerable<Object> objects { get; set; }
[BsonExtraElements]
public BsonDocument UnmappedFields { get; set; } // I'm not sure why it's required, something wrong with mapping configuration,
// but it's a separate question
}
public class Object
{
public int id { get; set; }
public IEnumerable<TrackingData> tracking_datas { get; set; }
}
public class TrackingData
{
public int id { get; set; }
public IEnumerable<int> polygons { get; set; }
[BsonExtraElements]
public BsonDocument UnmappedFields { get; set; } // I'm not sure why it's required, something wrong with mapping configuration,
// but it's a separate question
}
var json = #"{
""objects"": [
{
""id"": 123,
""tracking_datas"": [
{
""id"": 1,
""polygons"": [1,3]
},
{
""id"": 2,
""polygons"": [3]
},
{
""id"": 3,
""polygons"": [1,2]
}
]
}
]
}";
var client = new MongoClient();
var db = client.GetDatabase("so_test");
var coll = db.GetCollection<BsonDocument>("coll");
coll.InsertOne(BsonDocument.Parse(json));
var ids = new[] { 1, 2 };
var typedColl = db.GetCollection<Test>("coll");
var result = typedColl
.Aggregate()
.Project(p =>
new Test
{
Id = p.Id,
objects = p.objects.Select(o =>
new Object
{
id = o.id,
tracking_datas = o.tracking_datas.Where(t => t.polygons.Any(p=>ids.Contains(p)))
})
}
)
.ToList();
Here you go:
db.collection.find({
"objects.tracking_datas.polygons": {
$in: [
1,
2
]
}
})
https://mongoplayground.net/p/MDlIV3YPkZB
public class Job
{
public long Id { get; set; }
public long? JobId { get; set; }
public Job ParentJob { get; set; }
public ICollection<Job> ChildJobs { get; set; }
public string Name { get; set; }
}
var child = new Job { Name = "ChildJob" };
var parent = new Job { Name = "ParentJob", ChildJobs = new List<Job>()};
parent.ChildJobs.Add(child);
_context.Jobs.Add(parent);
_context.SaveChanges();
I added jobs like this: but why I get childJob duplicated?
[ { "id": 1, "jobId": null, "parentJob": null, "childJobs": [ { "id": 2, "jobId": 1, "childJobs": null, "name": "ChildJob" } ], "name": "ParentJob" }, { "id": 2, "jobId": 1, "parentJob": { "id": 1, "jobId": null, "parentJob": null, "childJobs": [], "name": "ParentJob" }, "childJobs": null, "name": "ChildJob" } ]
{
"_id": "111de970-4f3f-4ae6-9d3b-396e60ff50aa",
"ClaimNumber": 111,
"Details": [
{
"Amount": "100",
"Types": [
{
"InvoiceType": "OO",
"Status": "N"
},
{
"InvoiceType": "PP",
"Status": "N"
}
]
},
{
"Amount": "100",
"Types": [
{
"InvoiceType": "OO",
"Status": "N"
},
{
"InvoiceType": "SS",
"Status": "N"
}
]
}
]
}
public class Type
{
public string InvoiceType { get; set; }
public string Status { get; set; }
}
public class Detail
{
public string Amount { get; set; }
public List<Type> Types { get; set; }
}
public class RootObject
{
public string _id { get; set; }
public int ClaimNumber { get; set; }
public List<Detail> Details { get; set; }
}
I Would like to update the values of Types array "Status" = "P" in the Details array when the "_id" column and "Types.InvoiceType" = "OO" value matches.
Please provide me an example on how to achieve in c# using mongo driver.
There you go:
var filter = Builders<RootObject>.Filter.Eq(o => o._id, "111de970-4f3f-4ae6-9d3b-396e60ff50aa");
var update = Builders<RootObject>.Update.Set($"{nameof(RootObject.Details)}.$[].{nameof(Detail.Types)}.$[elem].{nameof(Type.Status)}", "P");
var arrayFilter = new JsonArrayFilterDefinition<BsonDocument>($"{{ 'elem.{nameof(Type.InvoiceType)}': 'OO' }}");
var updateOptions = new UpdateOptions { ArrayFilters = new[] { arrayFilter } };
var result = new MongoClient()
.GetDatabase("database")
.GetCollection<RootObject>("collection")
.UpdateOne(filter, update, updateOptions);
I want to create JSON object with following format:-
{
"result": [
{
"name": "John",
"address": "US",
},
{
"name": "Josh",
"address": "Japan",
}
],
"error": [
{
"message": "error-message"
}
],
"success": [
{
"message": "success-message"
}
]
}
I have tried the following, but it doesn't help me.
dynamic record = new { result = new {name="", address=""},
error = new {message=""},
success = new {message=""} };
Update 1:-
Here is my code:-
List addressList = new List();
// Loop over items within the container and URI.
foreach (var item in items)
{
dynamic record = new { result = new object[] {
new {name = item.name, address = item.address} } };
addressList.Add(record);
}
Result:-
[ {
"result": [
{
"name": "John",
"address": "US"
}
]
},
{
"result": [
{
"name": "Jack",
"address": "CA"
}
]
}
]
Expected json result:-
[{
"result": [{
"name": "John",
"address": "US"
}]
},
{
"result": [{
"name": "Jack",
"address": "CA"
}],
"error": [{
"message": "error-message"
}],
"success": [{
"message": "success-message"
}]
}
]
How do I update my code to get above expected json result?
You...create arrays. You're not doing that. You're creating individual objects.
Something along the lines of:
dynamic record = new {
result = new object[] {
new {name = "John", address = "US"},
new {name = "Josh", address = "Japan"}
},
error = new object[] /*...*/,
success = new object[] /*...*/
};
If you want exactly JSON, then newtonsoft.Json makes it easier:
Json json = new Json();
json.result = new object[] {
new {name = "John", address = "US"},
new {name = "Josh", address = "Japan"}
};
// json.error = ... and so on
string output = JsonConvert.SerializeObject(product);
The output you will have is:
{
"result": [
{
"name": "John",
"address": "US",
},
{
"name": "Josh",
"address": "Japan",
}
],
"error": [
{
...
}
]
}
To deserialize it back, use:
Json deserializedJson = JsonConvert.DeserializeObject<Json>(output);
you are not creating an array
if you want to create JSON arrays from c# you have to use the following POCO
public class Result
{
public string name { get; set; }
public string address { get; set; }
}
public class Error
{
public string message { get; set; }
}
public class Success
{
public string message { get; set; }
}
public class RootObject
{
public List<Result> result { get; set; }
public List<Error> error { get; set; }
public List<Success> success { get; set; }
}
and then use Json.net
var json = JsonConvert.SerializeObject( "your instance of the root Object")
//You need to make this class structure first
public class Response
{
public List<Result> result { get; set; }
public List<Error> error { get; set; }
public List<Success> success { get; set; }
}
public class Result
{
public string name { get; set; }
public string address { get; set; }
}
public class Error
{
public string message { get; set; }
}
public class Success
{
public string message { get; set; }
}
// And then you can use it like this
var response = new Response()
{
result = new List<Result>
{
new Result() {name = "Jhon", address = "US"},
new Result() {name = "Jhon", address = "US"},
},
error = new List<Error>()
{
new Error() {message = "error-message 1"},
new Error() {message = "error-message 2"}
},
success = new List<Success>()
{
new Success(){message = "success-message 1"},
new Success(){message = "success-message 2"},
}
};
The Model Class
public class MegaMenu
{
public int department_id { get; set; }
public string department_name { get; set; }
public List<SectionListData> sectionListData { get; set; }
}
public class SectionListData
{
public int section_id { get; set; }
public string section_name { get; set; }
public List<ItemHeadList> itemHeadList { get; set; }
}
public class ItemHeadList
{
public int item_head_id { get; set; }
public string item_name { get; set; }
}
public class WrapperMegaMenu
{
public List<MegaMenu> megaMenuList { get; set; }
public string error { get; set; }
}
The Services
dept_result is the array of all department,section_result is the array of all section,Item_result is the array of all items
List<MegaMenu> listmenu = new List<MegaMenu>();
foreach (var each_dept in dept_result)
{
MegaMenu megaMenu = new MegaMenu();
megaMenu.department_id = each_dept.shopdepartment_id;
megaMenu.department_name = each_dept.name_en;
var temSectionList = section_result
.Where(item => item.shopdepartment_id == each_dept.shopdepartment_id).ToList().Select(sectionData => new SectionListData
{
section_id = sectionData.shopsection_id,
section_name = sectionData.name_en,
itemHeadList = Item_result.Where(itemHead => itemHead.shopsection_id == sectionData.shopsection_id).ToList().Select(itemHeadData => new ItemHeadList {
item_head_id = itemHeadData.item_head_id,
item_name = itemHeadData.name_en
}).ToList()
}).ToList();
megaMenu.sectionListData = temSectionList;
listmenu.Add(megaMenu);
}
//wrapperDept.departmentList = dept_result.ToList();
wrapper.megaMenuList = listmenu.ToList();
Result
{
"megaMenuList": [
{
"department_id": 71,
"department_name": "Baby's Hygiene",
"sectionListData": [
{
"section_id": 56,
"section_name": "Diapers",
"itemHeadList": []
},
{
"section_id": 57,
"section_name": "Wipes",
"itemHeadList": [
{
"item_head_id": 142,
"item_name": "Telivision"
}
]
}
]
}
]
}
I am trying to deserialize the following JSON String:
Link to JSON String
{
"result": 1,
"error": null,
"id": 0,
"data": {
"ASTEALTHYNODE01_0301_0_30": {
"css_class": "sensor rf digital humidity",
"default_name": "Humidity",
"device_type": "humidity",
"did": "30",
"gid": "0301",
"has_subdevice_count": 0,
"has_time_series": 1,
"is_actuator": 0,
"is_sensor": 1,
"is_silent": 0,
"last_data": {
"DA": 58,
"timestamp": 1355791804474
},
"meta": {},
"node": "ASTEALTHYNODE01",
"shortName": "Humidity",
"subDevices": {},
"vid": "0"
},
"ASTEALTHYNODE01_0301_0_31": {
"css_class": "sensor rf digital temperature",
"default_name": "Temperature",
"device_type": "temperature",
"did": "31",
"gid": "0301",
"has_subdevice_count": 0,
"has_time_series": 1,
"is_actuator": 0,
"is_sensor": 1,
"is_silent": 0,
"last_data": {
"DA": 26.6,
"timestamp": 1355791804475
},
"meta": {},
"node": "ASTEALTHYNODE01",
"shortName": "Temperature",
"subDevices": {},
"vid": "0"
},
"ASTEALTHYNODE01_0_0_1000": {
"css_class": "actuator cape led rgbled",
"default_name": "On Board RGB LED",
"device_type": "rgbled",
"did": "1000",
"gid": "0",
"has_subdevice_count": 0,
"has_time_series": 0,
"is_actuator": 1,
"is_sensor": 1,
"is_silent": 0,
"last_data": {
"DA": "22B42B",
"timestamp": 1355790209080
},
"meta": {},
"node": "ASTEALTHYNODE01",
"shortName": "On Board RGB LED",
"subDevices": {},
"vid": "0"
},
"ASTEALTHYNODE01_0_0_11": {
"css_class": "sensor serial rf rf433 receiver transmitter",
"default_name": "RF 433Mhz",
"device_type": "rf433",
"did": "11",
"gid": "0",
"has_subdevice_count": 1,
"has_time_series": 0,
"is_actuator": 1,
"is_sensor": 1,
"is_silent": 0,
"last_data": {
"DA": "010001010101010100010101",
"timestamp": 1355789891324
},
"meta": {},
"node": "ASTEALTHYNODE01",
"shortName": "RF 433Mhz",
"subDevices": {
"6l8At": {
"category": "rf",
"data": "011111110001010100110000",
"shortName": "Door Bell",
"type": "sensor"
}
},
"vid": "0"
}
}
}
I usually create the classes with help of: http://json2csharp.com and then I am doing something like this (Json.NET libary):
Collapse | Copy Code
var result = JsonConvert.DeserializeObject<MyObject>(jsonString);
But the number of devices and their names (example: ASTEALTHYNODE01_0_0_11) are unknown before I get the JSON string. How can i deserialize this ?
Thank you
This works for me, with your JSON, and using JSON.NET:
Payload payloadJsonNet = JsonConvert.DeserializeObject<Payload>(data);
System.Diagnostics.Debug.Assert
(
payloadJsonNet.data.ContainsKey("ASTEALTHYNODE01_0_0_11") &&
payloadJsonNet.data["ASTEALTHYNODE01_0_0_11"].subDevices.ContainsKey("6l8At") &&
payloadJsonNet.data["ASTEALTHYNODE01_0_0_11"].subDevices["6l8At"].shortName == "Door Bell"
);
... provided you have prepared the following POCOs (using the nifty json2csharp helper, for example):
public class Payload
{
public int result { get; set; }
public int id { get; set; }
public Error error { get; set; }
public Dictionary<string, Device> data { get; set; }
}
public class Device
{
public string css_class { get; set; }
public string default_name { get; set; }
public string device_type { get; set; }
public string did { get; set; }
public string gid { get; set; }
public int has_subdevice_count { get; set; }
public int has_time_series { get; set; }
public int is_actuator { get; set; }
public int is_sensor { get; set; }
public int is_silent { get; set; }
public LastData last_data { get; set; }
public Meta meta { get; set; }
public string node { get; set; }
public string shortName { get; set; }
public Dictionary<string, Device> subDevices { get; set; }
public string vid { get; set; }
}
public class LastData
{
public string DA { get; set; }
public long timestamp { get; set; }
}
public class Meta
{
}
public class Error
{
}
I guess you'll have to find out / infer from other JSON inputs what should be the properties for these last two guys (i.e., "Meta" and "Error").
Note also, the "long" type that needs to be used in:
public class LastData
{
public string DA { get; set; }
public long timestamp { get; set; }
}
Finally, just for the curious, my own parser deserializes it fine as well:
Payload payloadMyParser = new JsonParser().Parse<Payload>(data);
System.Diagnostics.Debug.Assert
(
payloadMyParser.data.ContainsKey("ASTEALTHYNODE01_0_0_11") &&
payloadMyParser.data["ASTEALTHYNODE01_0_0_11"].subDevices.ContainsKey("6l8At") &&
payloadMyParser.data["ASTEALTHYNODE01_0_0_11"].subDevices["6l8At"].shortName == "Door Bell"
);
'Hope this helps,
Your json "data" property looks like property with type Dictionary < string, SomeClass>, where SomeClass - is a class for
{
"css_class": "sensor rf digital humidity",
// skipped
"subDevices": {},
"vid": "0"
},
data structure, so you may define this property in MyObject class and use strong typed deserialization without any problem.