Extract objects from JSON array with Newtonsoft JSON - c#

I have a JSON data like bellow
[{
"CurrencyDenomination_JSON": "[{\"PK_MasterCurrencyDenomID\":1,\"CurrencyDenomination\":2000,\"NoofCurrency\":2,\"Total\":\"4000.00\",\"IsNote\":true},{\"PK_MasterCurrencyDenomID\":2,\"CurrencyDenomination\":500,\"NoofCurrency\":2,\"Total\":\"1000.00\",\"IsNote\":true}]"
}, {
"CurrencyDenomination_JSON": "[{\"PK_MasterCurrencyDenomID\":1,\"CurrencyDenomination\":2000,\"NoofCurrency\":5,\"Total\":\"10000.00\",\"IsNote\":true},{\"PK_MasterCurrencyDenomID\":2,\"CurrencyDenomination\":500,\"NoofCurrency\":2,\"Total\":\"1000.00\",\"IsNote\":true}]"
}, {
"CurrencyDenomination_JSON": "[{\"PK_MasterCurrencyDenomID\":1,\"CurrencyDenomination\":2000,\"NoofCurrency\":5,\"Total\":\"10000.00\",\"IsNote\":true},{\"PK_MasterCurrencyDenomID\":2,\"CurrencyDenomination\":500,\"NoofCurrency\":5,\"Total\":\"2500.00\",\"IsNote\":true}]"
}]
and I want to extract value from it and expect bellow data
[{
"PK_MasterCurrencyDenomID": 1,
"CurrencyDenomination": 2000,
"NoofCurrency": 2,
"Total": "4000.00",
"IsNote": true
}, {
"PK_MasterCurrencyDenomID": 2,
"CurrencyDenomination": 500,
"NoofCurrency": 2,
"Total": "1000.00",
"IsNote": true
}, {
"PK_MasterCurrencyDenomID": 3,
"CurrencyDenomination": 200,
"NoofCurrency": 2,
"Total": "400.00",
"IsNote": true
}, {
"PK_MasterCurrencyDenomID": 4,
"CurrencyDenomination": 100,
"NoofCurrency": 2,
"Total": "200.00",
"IsNote": true
}, {
"PK_MasterCurrencyDenomID": 5,
"CurrencyDenomination": 50,
"NoofCurrency": 2,
"Total": "100.00",
"IsNote": true
}, {
"PK_MasterCurrencyDenomID": 6,
"CurrencyDenomination": 20,
"NoofCurrency": 2,
"Total": "40.00",
"IsNote": true
}]
to do that I write bellow code ,and think this is not right way to do that there must be some smart way to do that .Please suggest me a better alternative.
JArray jsonArray = JArray.Parse(json);
List<MasterCurrencyDenomination> d = new List<MasterCurrencyDenomination>();
string strjson = string.Empty;
foreach (var item in jsonArray.Children())
{
strjson+= item["CurrencyDenomination_JSON"].ToString().Replace("[", "").Replace("]", ",");
}
d = JsonConvert.DeserializeObject<List<MasterCurrencyDenomination>>("["+strjson+"]");

If you observe the Json, it is evident that it is an Array of Type which contains a single String Property CurrencyDenomination_JSON. The Value of CurrencyDenomination_JSON is a JSON string.
What you need to do is, fetch these JSON strings (represented as IEnumerable<string>), retrieve JObject from them by parsing each of them and Serialize the collection.
var currencyArray = JArray.Parse(json).Children<JObject>()
.SelectMany(x=>x.Properties().Select(c=>c.Value.Value<string>()));
var result = JsonConvert.SerializeObject(currencyArray.SelectMany(x=>JArray.Parse(x)));

I think You can use the following code to do this.
List<MasterCurrencyDenomination> items = new List<MasterCurrencyDenomination>();
JToken.Parse(myJson).ToList().ForEach(x =>
{
items.AddRange(JsonConvert.DeserializeObject<List<MasterCurrencyDenomination>>(x.SelectToken("CurrencyDenomination_JSON").Value<string>()));
});
OR:
List<MasterCurrencyDenomination> items2 = new List<MasterCurrencyDenomination>();
foreach (var test in JToken.Parse(myJson))
{
items2.AddRange(JsonConvert.DeserializeObject<List<MasterCurrencyDenomination>>(test.SelectToken("CurrencyDenomination_JSON").Value<string>()));
}

Related

Getting some strings with using Regex

Could someone help me how I can get the strings after the English > srt
I only wanna grab this strings:
/20200623/c1/51/1777469aba625657d69b3cbaefed1387.srt?qd_uid=0&qd_tm=1594275239930&qd_tvid=16385349500&qyid=f0f6a8fe625d5f29422131ad7c466dbf&lid=3
"_name": "Vietnamese",
"_sort": 6,
"mver": "101",
"lid": 23,
"xml": "/20200623/c0/72/e00ed17c479f2700194837e1d3901e32.xml?qd_uid=0&qd_tm=1594275239930&qd_tvid=16385349500&qyid=f0f6a8fe625d5f29422131ad7c466dbf&lid=23",
"srt": "/20200623/c0/72/41619b14d41606def042d6d267b72de2.srt?qd_uid=0&qd_tm=1594275239930&qd_tvid=16385349500&qyid=f0f6a8fe625d5f29422131ad7c466dbf&lid=23",
"_selected": false,
"pre": 0,
"ie": 0,
"uuid": "b908453e2869285ef8a1f75599ae85d9",
"_limited": 1,
"ssv": 1,
"webvtt": "/20200623/c0/72/cbc73fb5b7da5282d0697f265e08c87c.vtt?qd_uid=0&qd_tm=1594275239930&qd_tvid=16385349500&qyid=f0f6a8fe625d5f29422131ad7c466dbf&lid=23",
"ss": 0
},
{
"_name": "English",
"_sort": 1,
"mver": "101",
"lid": 3,
"xml": "/20200623/c1/51/445603c545708bf234430da417a9469f.xml?qd_uid=0&qd_tm=1594275239930&qd_tvid=16385349500&qyid=f0f6a8fe625d5f29422131ad7c466dbf&lid=3",
"srt": "/20200623/c1/51/1777469aba625657d69b3cbaefed1387.srt?qd_uid=0&qd_tm=1594275239930&qd_tvid=16385349500&qyid=f0f6a8fe625d5f29422131ad7c466dbf&lid=3",
"_selected": true,
"pre": 0,
"ie": 0,
"uuid": "c802506ad202e27680b8096ccc18f36d",
"_limited": 1,
"ssv": 1,
"webvtt": "/20200623/c1/51/da547e3c9d716037190173eabfbf4eaf.vtt?qd_uid=0&qd_tm=1594275239930&qd_tvid=16385349500&qyid=f0f6a8fe625d5f29422131ad7c466dbf&lid=3",
"ss": 0
I finally figure it out to get the English link only
string json = richTextBox1.Text;
JObject jObject = JObject.Parse(json);
var subtitle = jObject["data"]["program"]["stl"][8]["srt"]; //[8] is the English
output.Text = subtitle.ToString();

How can I filter Mongodb specific document's subdocument

Consider you have Order and OrderDetails. I'm trying to filter order details for the specific order.
For instance if you have document something like this:
{
"orders": [
{
"id": 1,
"date": "02.04.2020 ...",
"user": {
"name": "xx",
"surname": "yy"
},
"orderDetails": [
{
"id": 1,
"productId": 5,
"quantity": 1,
"state": 3
},
{
"id": 2,
"productId": 3,
"quantity": 4,
"state": 3
},
{
"id": 3,
"productId": 4,
"quantity": 12,
"state": 2
},
{
"id": 4,
"productId": 7,
"quantity": 8,
"state": 2
},
{
"id": 5,
"productId": 12,
"quantity": 9,
"state": 3
}
]
},
{
"id": 2,
"date": "01.04.2020 ...",
"user": {
"name": "xx",
"surname": "yy"
},
"orderDetails": [
{
"id": 6,
"productId": 5,
"quantity": 1,
"state": 3
},
{
"id": 7,
"productId": 3,
"quantity": 4,
"state": 3
},
{
"id": 8,
"productId": 4,
"quantity": 12,
"state": 2
}
]
}
}
What I'm trying to do is first filtering by order and then state of an order detail. I have a code like this but it always brings correct order with all orderDetails. Seems like it doesn't care about equal filter for orderDetails.
Actually it's working but not filtering. Because I only have 3 types of state(enum) and int values are 1,2,3. Query brings nothing if I give 4.
var builder = Builders<Order>.Filter;
var filter = builderk.And(builder.Eq("_id", ObjectId.Parse(elementid)), builder.Eq("orderDetails.state", 3));
var result = _mongoRepository.FindByFilter(filter).ToList();
I also tried AnyEq and something like that filters but didn't work.
I will be very happy if anyone can help me.
Thanks.
You can use aggregation operation for operations such as filter sorting in detail records.
If we continue through the sample, you must first create a filter for your master data.
var builderMaster = Builders<Order>.Filter;
var filterMaster = builderMaster.Eq("_id", ObjectId.Parse(elementid));
Then you need to create a different filter for the details.
Important: You must use the BsonDocument type when creating detail filters. Because you cannot give a specific type when you filter the details.
var builderDetail = Builders<BsonDocument>.Filter;
var filterDetail = builderDetail.Eq("orderDetails.state", 3);
Then you can start typing the query.
var list = _mongoRepository.Aggregate()
.Match(filterMaster)
.Unwind("orderDetails")// Name the details.
.Match(filterDetail)
.Sort(sort)// optionally
.Skip(skip) // optionally
.Limit(limit) // optionally
.ToList();
It will give you a list of BsonDocument with the given parameters. After that, you have to map with your own detail class.
var resultList = new List<OrderDetails>();
foreach (var master in list)
{
var masterObj = BsonSerializer.Deserialize<dynamic>(master);
foreach (var item in masterObj)
{
if (item.Key == "orderDetails")
{
var mapper = new MapperConfiguration(cfg => { }).CreateMapper();
var retItem = mapper.Map<OrderDetails>(item.Value);
resultList.Add(retItem);
}
}
}

Merge 2 JSON Files Newtonsoft

I have 2 json files, or String and i want to merge them based on ID. Like join on sql. This is the example:
This is Json 1:
{
"City": [{
"CityId": 9,
"CityName": "Kukes"
}, {
"CityId": 18,
"CityName": "Tirana"
}, {
"CityId": 19,
"CityName": "Vlore"
}, {
"CityId": 22,
"CityName": "temp"
}]
}
And this i json 2:
{
"Citizen": [{
"CitizenId": 38,
"CitizenLastName": "Bale",
"CitizenName": "Christian",
"City_Id": 19
}, {
"CitizenId": 39,
"CitizenLastName": "ttrtrt",
"CitizenName": "test",
"City_Id": 18
}, {
"CitizenId": 42,
"CitizenLastName": "Freeman",
"CitizenName": "Morgan",
"City_Id": 9
}, {
"CitizenId": 43,
"CitizenLastName": "Snow",
"CitizenName": "Jon",
"City_Id": 9
}, {
"CitizenId": 44,
"CitizenLastName": "test2",
"CitizenName": "test",
"City_Id": 9
}]
}
I want it to merge in a json file or string based on id like this structure:
{
"City":
[
{
"CityId":9,
"CityName":"Kukes",
"Citizens" : [{"CitizenId":42,"CitizenLastName":"Freeman","CitizenName":"Morgan","City_Id":9},{"CitizenId":43,"CitizenLastName":"Snow","CitizenName":"Jon","City_Id":9},{"CitizenId":44,"CitizenLastName":"test2","CitizenName":"test","City_Id":9}]
},
{
"CityId":18,
"CityName":"Tirana",
"Citizens" : [{"CitizenId":39,"CitizenLastName":"ttrtrt","CitizenName":"test","City_Id":18}]
},
{
"CityId":19,
"CityName":"Vlore",
"Citizens" : [{"CitizenId":38,"CitizenLastName":"Bale","CitizenName":"Christian","City_Id":19}]
},
{
"CityId":22,
"CityName":"temp",
"Citizens" : []
}
]
}
I've tried all day and still found nothing. Do you have any idea how to do this with Newtonsoft? Or any other way? But I'd like it with newtonsoft.
You can do this with LINQ to JSON, using ToLookup() to find all citizens for a given city:
var cities = JToken.Parse(cityJson);
var citizens = JToken.Parse(citizenJson);
var lookup = citizens.SelectTokens("Citizen[*]").ToLookup(c => (string)c["City_Id"]);
foreach (var city in cities.SelectTokens("City[*]"))
{
city["Citizens"] = new JArray(lookup[(string)city["CityId"]]);
}
Prototype fiddle.
To load your JSON from a file, then later save back, see Read JSON from a file and Write JSON to a file.

How Will I get the value of certain things from json?

I have the following json string.
{
"items": {
"642163": {
"id": 642163,
"nm": "AK-21699-11-Lancer-Mohammed Al Noman",
"uid": "356307041429068",
"ph": "+971561755362",
"hwid": 216940,
"pos_x": 55.3744512,
"pos_y": 25.335552,
"pos_z": 50,
"pos_t": 1395383860,
"pos_sc": 7,
"hdop": 1.3,
"lmsg": {
"t": 1395383860,
"f": 3,
"tp": "ud",
"pos": {
"y": 25.335552,
"x": 55.3744512,
"z": 50,
"s": 0,
"c": 0,
"sc": 7
},
"i": 0,
"p": {
"param179": 0,
"param180": 1,
"param69": 1,
"param175": 1,
"param182": 13,
"hdop": 1.3,
"pwr_ext": 12.978,
"battery_charge": 0
}
},
"param180": 1,
"param69": 1,
"param182": 13,
"pwr_ext": 12.978,
"cnm": 71869,
"cnkb": 2400,
"cneh": 2160,
"client_name": "Al Kharafi",
"access_code": "sms,sms",
"serial_no": "2837965",
"vreg_number": "21699",
"instln_date": "1/14/2013",
"vehicle_type": "car_saloon",
"contact_ph": "branches"
}
},
"sid": "b96c9de5b4c609f905219c20b113f712",
"count": 12,
"p_type": "hst"
}
I want to get the id,nm,p and pos.How will i get it in asp.net c#?
Grab the JSON.NET library. It's available via NuGet under that name.
using Newtonsoft.Json.Linq;
Now you can pull data out of your JSON string yourText as in the following example.
var token = JToken.Parse(yourText);
var nm = token["items"]["642163"]["nm"].ToObject<string>();
nm will have the value AK-21699-11-Lancer-Mohammed Al Noman.

what is the best way to generate json from C#

i am trying to mimic an example where they are using hard coded JSON
{
"page": 1,
"total": 1,
"records": 2,
"rows": [
{"id": 1, "cell": ["1", "Super Item", "300", 0, null, false, false]},
{"id": 2, "cell": ["2", "Item 1", "100", 1, 1, false, false]},
{"id": 3, "cell": ["3", "Sub Item 1", "50", 2, 2, true, true]},
{"id": 4, "cell": ["4", "Sub Item 2", "25", 2, 2, false, false]},
{"id": 5, "cell": ["5", "Sub-sub Item 1", "25", 3, 4, true, true]},
{"id": 6, "cell": ["6", "Sub Item 3", "25", 2, 2, true, true]},
{"id": 7, "cell": ["7", "Item 2", "200", 1, 1, false, false]},
{"id": 8, "cell": ["8", "Sub Item 1", "100", 2, 7, false, false]},
{"id": 9, "cell": ["9", "Sub-sub Item 1", "50", 3, 8, true, true]},
{"id": 10, "cell": ["10", "Sub-sub Item 2", "50", 3, 8, true, true]},
{"id": 11, "cell": ["11", "Sub Item 2", "100", 2, 7, true, true]}
]
}
but i need to generate this from C#. Are there any suggestions for the best way to go about generating this above in C#?
The Controller class has a Json method that serialises objects as JSON, so in your action method you just create the object and call the method:
public ActionResult GetData() {
return Json(
new {
page = 1,
total = 1,
records = 2,
rows = new[] {
new { id = 1, cell = new object[] { "1", "Super Item", "300", 0, null, false, false } },
new { id = 2, cell = new object[] { "2", "Item 1", "100", 1, 1, false, false } },
new { id = 3, cell = new object[] { "3", "Sub Item 1", "50", 2, 2, true, true } },
new { id = 4, cell = new object[] { "4", "Sub Item 2", "25", 2, 2, false, false } },
new { id = 5, cell = new object[] { "5", "Sub-sub Item 1", "25", 3, 4, true, true } },
new { id = 6, cell = new object[] { "6", "Sub Item 3", "25", 2, 2, true, true } },
new { id = 7, cell = new object[] { "7", "Item 2", "200", 1, 1, false, false } },
new { id = 8, cell = new object[] { "8", "Sub Item 1", "100", 2, 7, false, false } },
new { id = 9, cell = new object[] { "9", "Sub-sub Item 1", "50", 3, 8, true, true } },
new { id = 10, cell = new object[] { "10", "Sub-sub Item 2", "50", 3, 8, true, true } },
new { id = 11, cell = new object[] { "11", "Sub Item 2", "100", 2, 7, true, true } }
}
}
);
}
There's a class built into .Net 2+ which is called 'JavaScriptSerializer' which creates a JSON structured string based on a .Net typed class.
Using the serializer you can simply created a class with properties and collections to represent your JSON data. Create an instance of it in .Net server side code and then respond using the serializer to generate a valid JSON string response.
Here's an example of converting a Person class instance to a serialized JSON string;
JavaScriptSerializer js = new JavaScriptSerializer();
Person p1 = new Person();
p1.firstName = "Brian";
p1.lastName = "Scott";
p1.department = "Microsoft";
p1.address.addressline1 = "Microsoft";
p1.address.addressline2 = "";
p1.address.city = "Redmond";
p1.address.state = "Seattle";
p1.address.country = "America";
p1.address.pin = 560028;
p1.technologies = new string[] { "IIS", "ASP.NET", "JavaScript", "AJAX" };
string strJSON = js.Serialize(p1);
This will produce a valid JSON string of
{"firstName":"Brian","lastName":"Scott","department":"Microsoft","address":{"addressline1":"Microsoft","addressline2":"","city":"Redmond","state":"Seattle","country":"America","pin":560028},"technologies":["IIS","ASP.NET","JavaScript","AJAX"]}
If you are intending to use a webservice to produce the JSON response to the client side then you can mark your method as;
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetPersonJSON()
{
JavaScriptSerializer js = new JavaScriptSerializer();
Person p1 = new Person();
p1.firstName = "Brian";
p1.lastName = "Scott";
p1.department = "Microsoft";
p1.address.addressline1 = "Microsoft";
p1.address.addressline2 = "";
p1.address.city = "Redmond";
p1.address.state = "Seattle";
p1.address.country = "America";
p1.address.pin = 560028;
p1.technologies = new string[] { "IIS", "ASP.NET", "JavaScript", "AJAX" };
return js.Serialize(p1);
}
Apparently you are trying to populate a jqGrid and you're using ASP.NET MVC.
If you have defined a class for these values:
["1", "Super Item", "300", 0, null, false, false]
You can store all the elements in a collection myCollection
you can do something like this:
var ReturnData = new
{
total = totalPages,
page = page,
records = totalRecords,
rows = myCollection.Select(r => new
{
id = r.Id.ToString(),
cell = new String[] { r.Field1, r.Field2, r.Field3, r.Field4 }
})
};
return (Json(ReturnData, JsonRequestBehavior.DenyGet));
class Row {
public int id {get;set;}
public object[] cell {get;set;}
}
class Data {
public int page {get;set;}
public int total {get;set;}
public int records {get;set;}
public Row[] rows {get;set;}
}
var myData = new Data(){ .... };
var json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(myData);

Categories

Resources