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);
Related
How to covert the below json
{"data":{"id":12,"name":"jeremy","email":"jeremy#test.com"}}
to
{"id":12,"name":"jeremy","email":"jeremy#test.com"}
I want to remove the "data" element from json.
With json.net it's fairly straightforward
var input = "{\"data\":{\"id\":12,\"name\":\"jeremy\",\"email\":\"jeremy#test.com\"}}";
var result = JObject.Parse(input)["data"].ToString(Formatting.None);
Console.WriteLine(result);
Note : Formatting.None is only to preserve the formatting you had in your original example
Or Text.Json
var result = JsonDocument.Parse(input).RootElement.GetProperty("data").ToString();
Output
{"id":12,"name":"jeremy","email":"jeremy#test.com"}
Additional Resources
JObject.Parse Method (String)
Load a JObject from a string that contains JSON.
JObject.Item Property (String)
Gets or sets the JToken with the specified property name.
JToken.ToString Method (Formatting,JsonConverter[])
Returns the JSON for this token using the given formatting and
converters.
Formatting Enumeration
None 0 No special formatting is applied.
Text.Json
JsonDocument.Parse Method
Provides a mechanism for examining the structural content of a JSON
value without automatically instantiating data values.
JsonDocument.RootElement Property
Gets the root element of this JSON document
JsonElement.GetProperty Method
Gets a JsonElement representing the value of a required property
identified by propertyName.
I have a follow up question on a scenario where I don't want to remove the root element.
{
"keepMe": {
"removeMe": [
{
"id": "1",
"name": "Foo",
"email": "Foo#email.com"
},
{
"id": "2",
"name": "Bar",
"email": "Bar#email.com"
}
]
}
But I wanted it to look like
{
"keepMe": {
{
"id": "1",
"name": "Foo",
"email": "Foo#email.com"
},
{
"id": "2",
"name": "Bar",
"email": "Bar#email.com"
}
}
Using below would not work. Is there another way to do this?
var result = JObject.Parse(input)["keepMe"]["removeMe"].ToString(Formatting.None);
//{
// "id": "1",
// "name": "Foo",
// "email": "Foo#email.com"
//},
//{
// "id": "2",
// "name": "Bar",
// "email": "Bar#email.com"
//}
var result = JObject.Parse(input)["removeMe"].ToString(Formatting.None); //Null Reference
Found the answer using the SelectToken and Replace keyword
var jObj = JObject.Parse(input);
jObj.SelectToken("keepMe").Replace(jObj.SelectToken("keepMe.removeMe"));
string result = jObj.ToString();
What has been done so far?
I am working on dividing up the number of records into 3 batches and processing them in parallel to increase the performance. However, after processing the batches in parallel I would also like to save the outcome (JSON string) of the processed records in a variable.
As you can see below, I first initialize the variable as List of string and then run the foreach loop which saves the processed outcome as mentioned below.
List<string> responseOutcome = new List<string>();
Parallel.ForEach(recordBatches, batch => {
responseOutcome.Add(response1.Content);
});
Result in List responseOutcome comes as:
responseOutcome[0]
[
{
"Name": "Sample1",
"ID": "123"
},
{
"Name": "Sample2",
"ID": "394"
}
],
responseOutcome[1]
[
{
"Name": "Sample5",
"ID": "384"
},
{
"Name": "Sample6",
"ID": "495"
}
],
responseOutcome[2]
[
{
"Name": "Sample3",
"ID": "473"
},
{
"Name": "Sample4",
"ID": "264"
}
]
What I would like to achieve?
Now I would like to take the value of responseOutcome which is multiple arrays of JSON string and merge them into one big JSON string.
Final Output
[
{
"Name": "Sample1",
"ID": "123"
},
{
"Name": "Sample2",
"ID": "394"
},
{
"Name": "Sample5",
"ID": "384"
},
{
"Name": "Sample6",
"ID": "495"
},
{
"Name": "Sample3",
"ID": "473"
},
{
"Name": "Sample4",
"ID": "264"
}
]
I looked into several similar cases but they weren't nearly similar. Like:
How do I merge multiple json objects
How do I combine two arrays from two JObjects in Newtonsoft JSON.Net?
Any help/guidance will be great!!
Using Newtonsoft, you can create a JArray from each of your responses. Then you can flatten the hierarchy using linq's SelectMany method and re-serialize the object.
Try this:
var obj = responses.Select(r => JArray.Parse(r.Trim(','))).SelectMany(token => token);
string json = JsonConvert.SerializeObject(obj, Formatting.Indented);
There are probably more efficient ways to do this if you want to do pure string manipulation, but using Newtonsoft, I would deserialize, merge and then re-serialize.
Create a small POCO model:
public class ResponseOutcomeModel
{
public string ID { get; set; }
public string Name { get; set; }
}
Then deserialize to this model, merge and reserialize to JSON as a single list.
var outcomeList = new List<ResponseOutcomeModel>();
foreach (var i in responseOutcome)
{
outcomeList.AddRange(JsonConvert.DeserializeObject<List<ResponseOutcomeModel>>(i.Trim().TrimEnd(',')));
}
var finalJson = JsonConvert.SerializeObject(outcomeList);
Note, the Time/TrimEnd is used if the trailing commas in your example are really there in your responseOutcome array (at the end of each element in the array). The call to DeserializeObject will complain if you leave the commas in there.
I can not figure out exactly how to did through this JObject in order to retrieve the id property under runs.
I have this following code which will successfully give me the id property that is under entries, but how can I nest this again to go into the runs sections and get those ID's?
JSON:
{
"id": 168,
"name": "section 1",
"entries": [
{
"id": "908-9876-908",
"suite_id": 15,
"name": "List 1",
"runs": [
{
"id": 169,
"suite_id": 15
}
]
},
{
"id": "998-4344-439",
"suite_id": 16,
"name": "List 2",
"runs": [
{
"id": 170,
"suite_id": 16
}
]
}
]
}
C# Code:
JObject obj = JsonConvert.DeserializeObject<JObject>(response);
foreach (JObject id in obj["entries"])
{
string returnable = (string)id["id"];
Console.WriteLine(returnable);
}
I have tried looking at ["entries"]["runs"] but that also was not working.
The print out of this is:
908-9876-908
998-4344-439
What I would like is
169
170
You can achieve it using the following code
var jsonObject = JObject.Parse(json);
foreach (var entry in jsonObject["entries"])
{
foreach (var run in entry["runs"])
{
string returnable = (string)run["id"];
Console.WriteLine(returnable);
}
}
You would like to see
169
170
They are an id values from runs array, therefore you should enumerate them in the inner loop. You've also missed a comma after "name": "section 1"
You can use SelectTokens() to query for nested data inside a JToken hierarchy. It provides support for JSONPath queries including wildcards [*] for arrays:
var ids = obj.SelectTokens("entries[*].runs[*].id").Select(i => (long)i).ToList();
See: Querying JSON with complex JSON Path.
Demo fiddle here.
starting from a JObject I can get the array that interests me:
JArray partial = (JArray)rssAlbumMetadata["tracks"]["items"];
First question: "partial" contains a lot of attributes I'm not interested on.
How can I get only what I need?
Second question: once succeeded in the first task I'll get a JArray of duplicated items. How can I get only the unique ones ?
The result should be something like
{
'composer': [
{
'id': '51523',
'name': 'Modest Mussorgsky'
},
{
'id': '228918',
'name': 'Sergey Prokofiev'
},
]
}
Let me start from something like:
[
{
"id": 32837732,
"composer": {
"id": 245,
"name": "George Gershwin"
},
"title": "Of Thee I Sing: Overture (radio version)"
},
{
"id": 32837735,
"composer": {
"id": 245,
"name": "George Gershwin"
},
"title": "Concerto in F : I. Allegro"
},
{
"id": 32837739,
"composer": {
"id": 245,
"name": "George Gershwin"
},
"title": "Concerto in F : II. Adagio"
}
]
First question:
How can I get only what I need?
There is no magic, you need to read the whole JSON string and then query the object to find what you are looking for. It is not possible to read part of the JSON if that is what you need. You have not provided an example of what the data looks like so not possible to specify how to query.
Second question which I guess is: How to de-duplicate contents of an array of object?
Again, I do not have full view of your objects but this example should be able to show you - using Linq as you requested:
var items = new []{new {id=1, name="ali"}, new {id=2, name="ostad"}, new {id=1, name="ali"}};
var dedup = items.GroupBy(x=> x.id).Select(y => y.First()).ToList();
Console.WriteLine(dedup);
I want to select objects from a JSON string by filtering using a JSONPath expression with another expression embedded in the filter. In other words, I want to filter for a value that is present elsewhere in the JSON data.
For example:
In the following JSON data there is a value in $.Item.State.stepId (currently "QG2.0"). I need to have a JSONPath expression that selects values based on this value, like this:
$..Step[?(#.stepId==$Item.State.stepId)].actionDate
But this will not return any results. If I use the string ("QG2.0") directly like this:
$..Step[?(#.stepId=='QG2.0')].actionDate
it will return the required data.
What's wrong, or is it not even possible? My JSON is below:
{
"Item": {
"Common": {
"folio": "PSH-000016020",
"setName": "123-XZ200-1",
"wfId": "Kat1_002",
"wfIssue": "002",
"wfIdIssue": "Kat1_002.002"
},
"State": {
"status": "IN WORK",
"stepId": "QG2.0",
"stepDescription": "Validation"
},
"Participants": {
"Participant": [
{
"role": "PR",
"roleDescription": "Product Responsible",
"loginName": "marc102",
"email": "mark#abc.de"
}, {
"role": "CR",
"roleDescription": "Chapter Responsible",
"loginName": "uli26819",
"email": "uli#abc.de"
}
]
},
"Steps": {
"Step": [
{
"stepId": "QG1.0",
"stepTitle": "Preparation",
"actionDate": "2016-06-28T10:28:09",
"actionDueDate": "",
"actionBy_Name": "Marc",
"actionBy_Account": "marc102",
"action": "complete",
"Comment": ""
}, {
"stepId": "QG2.0",
"stepTitle": "Check Requirements",
"actionDate": "2016-08-08T14:17:04",
"actionDueDate": "",
"actionBy_Name": "Uli",
"actionBy_Account": "uli26819",
"action": "complete",
"Comment": ""
}
]
}
}
}
I don't think Json.Net's implementation of JSONPath supports this concept.
However, you can still get the information you want if you break the query into two steps:
JObject obj = JObject.Parse(json);
JToken stepId = obj.SelectToken("Item.State.stepId");
JToken actionDate = obj.SelectToken(string.Format("$..Step[?(#.stepId=='{0}')].actionDate", stepId));
Console.WriteLine(actionDate.ToString());
Fiddle: https://dotnetfiddle.net/KunYTf