Good morning everyone. I have a service which returns me a JSON response (something like below):
{
"sessionid": "AQIC5wM2LY4SfcytTIcteNkTtCVrE8A-AS7VR*",
"Customers": [
{
"id": "4193942846",
"firstname": "Anto",
"lastname": "Paul",
"customertype": "ph",
"companyCode": "ABCD",
},
{
"id": "4193942236",
"firstname": "Dimple",
"lastname": "Paul",
"customertype": "ph",
"companyCode": "AB",
}
],
"Status": "ACTIVE",
"serviceStatus": "SUCCESS",
"Addresses": {
"Address": [
{
"type": "M",
"addr1": "11011, main st",
"addr2": "Apt. 2",
"zipcode": "11011"
}
]
}
}
The above structure varies based on the input I pass to the service. So, I cant contruct one class to deserialize the response. I need to compare (attribute-attribute comparison) this response to a response I already have with me (in a different place).
I tried to do it with dynamic class in C# but no luck so far. Could someone share a better,working approach? Thank you.
You can use JToken.DeepEquals like this:
var response = JObject.Parse(responseJson);
var goldenStandard = JObject.Parse(goldenStandardJson);
if (JToken.DeepEquals(response, goldenStandard))
{
// the two JSONs have the same data
}
Try Json.Net. It supports dynamic structures.
Here is a tutorial:
http://www.codeproject.com/Tips/631586/Dynamic-types-with-JSON-NET
Use this:
https://jsonutil.codeplex.com/
var obj1 = JSONSerializer.Deserialize(jsontext1);
var obj2 = JSONSerializer.Deserialize(jsontext2);
bool Compare(object obj1, object obj2)
{
//if(obj1 is JSONObject && obj2 is JSONObject)
// => typecase and use jsonObj1.Members to iterate over members and compare values recursively
//if JSONArray, then iterate over items and compare
//if anything else... i.e. primitive then compare directly
//else return false;
}
If you are using this JSON response one time, then you can use a dynamic JSON NET types.
But if you are using this JSON structure response some times, then it is preferable to make this response to a c# classes (objects), so you will have a very easy access to it's properties, you just have your c# objects and they have properties and you can simply approach to each field you wish (with intellisense). By the way, it is very easy to copy a JSON response to a C# classes (something like copy paste). Here is how to do that:
http://blogs.msdn.com/b/webdev/archive/2012/12/18/paste-json-as-classes-in-asp-net-and-web-tools-2012-2-rc.aspx
Related
I have this JSON that's a list of objects, like this.
"Fields": [
{
"fieldID": 1,
"name": "field"
}
]
When the list is empty, it is sent like this
"Fields": [
{}
]
I read this in as a string and then try to deserialize it using JsonConvert.DeserializeObject<List<T>>(json); where T is the object that matches the field model. When I do this though, I get a new list with one item in it (count = 1 when it should be 0), the same as if I deserialized this JSON.
"Fields": [
{
"fieldID": 0,
"name": null
}
]
How can I avoid or work around this?
First following json does not represent empty list:
"Fields": [
{}
]
An empty list in json should look like following:
"Fields": []
So you should try to fix the json. However, if that's proven to be impossible you can do something like following:
using (JsonDocument document = JsonDocument.Parse(jsonString))
{
JsonElement root = document.RootElement;
var l = root.EnumerateArray().First().ToString();
if(l=="{}")
{
//do something
}
}
What's happening is that you simply parsing the json and enumerate through the list of element and detect if "{}" exists.
Or, you can go with a more complex way which is writing a custom converter which handles such case in the way you want. You can check out the documentation here
I am learning C# and I am trying to parse json/xml responses and check each and every key and value pair. For xml I am converting to json so I have only one function/script to work with both cases. My issue is that I am working with a wide range of json responses which are not similar and there may be arrays in some of the json response. I have tried accessing the "Count" of the json object as a way to check for arrays.
Note: The responses will vary. This example is for Products > Product > name, quantity and category. The next response will change and can be like Country > State > Cities and so on. I cannot rely on creating classes since all responses are going to be different. Plus I am working on automating it so it should be able to handle anything thrown at it.
Sample Json I am working with:
{
"products": {
"product": [
{
"name": "Dom quixote de La Mancha",
"quantity": "12",
"category": "Book"
},
{
"name": "Hamlet",
"quantity": "3",
"category": "Book"
},
{
"name": "War and Peace",
"quantity": "7",
"category": "Book"
},
{
"name": "Moby Dick",
"quantity": "14",
"category": "Book"
},
{
"name": "Forrest Gump",
"quantity": "16",
"category": "DVD"
}
]
}
The way I am accessing the count, name and value is as follows:
dynamic dyn = JsonConvert.DeserializeObject<dynamic>(jsonText);
foreach (JProperty property in dyn.Properties())
{
string propname = property.Name;
var propvalue = property.Value;
int count = property.Count;
}
Is there a way to access these without going through the foreach loop like int count = dyn.Count ? All I am getting from this is null instead of actual values.
For the above example my end result will be like:
This responses contains products> product> 5 x (name, quantity, category)
The QuickWatch for the object:
QuickWatch for dyn object
Try to deserialize your JSON into JObject like below:
var jObject = JsonConvert.DeserializeObject<JObject>(jsonText);
The only way I could figure out what the JSON response could be deserialized to was to look for strings within the JSON to give me a hint on what it could be. This seems very hacky and hoping there is a better way.
Given the 2 example JSON responses, how would I deserialize to the proper static type?
The result field could contain any simple or complex type.
In the first example results would be a list of names and the second would be a list of prices.
{
"jsonrpc": "2.0",
"id": 1,
"result": [ "Jane Doe", "Joe Smith" ]
}
{
"jsonrpc": "2.0",
"id": 1,
"result": [ 123, 456 ]
}
I'm trying to pull one specific piece of data from the json received from a geocoding request.
This is not a duplicate of the myriads of similar-sounding questions, because the json is dynamic and has extremely irregular arrays that change slightly between responses, so I can't create a model to parse to, neither can I navigate through it using key names.
This is the json of one response:
{
"Response":{
"MetaInfo":{
"Timestamp":"2019-07-28T13:23:04.898+0000"
},
"View":[
{
"_type":"SearchResultsViewType",
"ViewId":0,
"Result":[
{
"Relevance":1.0,
"MatchLevel":"houseNumber",
"MatchQuality":{
"City":1.0,
"Street":[
0.9
],
"HouseNumber":1.0
},
"MatchType":"pointAddress",
"Location":{
"LocationId":"NT_Opil2LPZVRLZjlWNLJQuWB_0ITN",
"LocationType":"point",
"DisplayPosition":{
"Latitude":41.88432,
"Longitude":-87.63877
},
"NavigationPosition":[
{
"Latitude":41.88449,
"Longitude":-87.63877
}
],
"MapView":{
"TopLeft":{
"Latitude":41.8854442,
"Longitude":-87.64028
},
"BottomRight":{
"Latitude":41.8831958,
"Longitude":-87.63726
}
},
"Address":{
"Label":"425 W Randolph St, Chicago, IL 60606, United States",
"Country":"USA",
"State":"IL",
"County":"Cook",
"City":"Chicago",
"District":"West Loop",
"Street":"W Randolph St",
"HouseNumber":"425",
"PostalCode":"60606",
"AdditionalData":[
{
"value":"United States",
"key":"CountryName"
},
{
"value":"Illinois",
"key":"StateName"
},
{
"value":"Cook",
"key":"CountyName"
},
{
"value":"N",
"key":"PostalCodeType"
}
]
}
}
}
]
}
]
}
}
I'm trying to get just the two coordinates inside NavigationPosition.
Before I start the tedious work of creating a method to manually pull out the data I need from the unparsed string, does anyone have a solution? Is there a way to iterate anonymously through the json arrays using a foreach or if statement?
If the response is dynamic then one option is to use dynamic deserialization
var dynamicObject = JsonConvert.DeserializeObject<dynamic>(jsonAsString);
You can iterate this object and write defensive code by checking null.
I am assuming that "NavigationPosition" will always lie under "location" and in turn under a list of "Result" under list of "View"
something like this.. (symbolic code)
if(dynamicObject.View != null && dynamicObject.View[0] != null && dynamicObject.View[0].Result[0] != null && dynamicObject.View[0].Result[0].Location != null )
{
var navigationPosition = dynamicObject.View[0].Result[0].Location.NavigationPosition;
// do something with it
}
It seems really cumbersome but if you have no control over json response, I think you should be able to get it right after some iterations :)
i have an object that is being passed to me from a json obj, each time it is has different feilds, i am using json.net to parse it, it is parsing it correctly and it is putting it in a list of obj
the format after serialization is:
{
"language": "EN",
"code": "test",
"name": "test",
"value": "TEST",
"id": "2222222222222222"
}
the fields are dynamic it can be up to 50 not just 5
any idea on how to parse it??
If you know the items in above format. you could create an typed object. and then you can use DataContractJsonSerializer like below.
DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(List<Student>));
List<Student> result = obj.ReadObject(stream) as List<myClass>;