Ways to parse Json recursive [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
My problem is that I need to parse json to another json format, I need to do that recursive. I have been tried diferents way but any works fine for me.
I would like to know more ways for test.
Thanks!
{
"items": {
"itemName": {
"type": "type",
"properties": {
"item1": {
"type": 1,
"isValid": true
},
"item2": {
"type": 1,
"isValid": true
}
}
}
}
}
And I need to make this
{
"items":{
"item1": 1,
"item2": 1
}
}

You can try with JToken to read the JSON and JsonConvert to convert the object to desired JSON
using (StreamReader r = new StreamReader(filepath))
{
var inputString = r.ReadToEnd();
JToken outer = JToken.Parse(inputString);
JObject inner = outer["items"]["itemName"]["properties"].Value<JObject>();
List<string> keys = inner.Properties().Select(p => p.Name).ToList();
var items = new ExpandoObject() as IDictionary<string, Object>;
foreach (string k in keys)
{
items.Add(k, Convert.ToInt32(outer["items"]["itemName"]["properties"][k]["type"]));
}
Console.WriteLine(JsonConvert.SerializeObject(new { items = items }));
}
output
{"items":{"item1":1,"item2":2}}

Related

How to get JSON Object using given path in string variable c# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
var string = "test.data"
var json = "{'test':{'data':[{'details':{'id':'1','name':'user1'}},{'details':{'id':'2','name':'user2'}}]}}"
var output = json.string
You can try JsonPath for getting value based on path,
var json = JObject.Parse(#"{
'test':{
'data':[
{
'details':
{
'id':'1',
'name':'user1'
}
},
{
'details':
{
'id':'2',
'name':'user2'
}
}
]
}
}");
JToken data = json.SelectToken("$.test.data");
Console.WriteLine(data);
.Net Fiddle
I believe this is what you are asking for, newtonsoft json library has been used in my example.
var json = "{'test':{'data':[{'details':{'id':'1','name':'user1'}},{'details':{'id':'2','name':'user2'}}]}}";
var jObj = JObject.Parse(json);
var result = jObj.SelectToken("test.data")?.ToString();
// result
// [
// {
// "details": {
// "id": "1",
// "name": "user1"
// }
// },
// {
// "details": {
// "id": "2",
// "name": "user2"
// }
// }
// ]
To read the JSON file using its path. You can create a common method that accepts the path and you can read it.
using System;
using System.IO;
public static string ReadAllTextFromPath(string path)
{
var filePath= AppDomain.CurrentDomain.BaseDirectory + path;
var fileData = File.ReadAllText(filePath);
return fileData ;
}
If you want to convert the JSON string into an object then use the below.
var jsonString = ReadAllTextFromPath(filepath);//your JSON string
var jObject = Newtonsoft.Json.Linq.JObject.Parse(jsonString);
if you want to select a particular value from a JSON data, use the selecttoken
var object = (string)jObject.SelectToken("test.data");
//If you know "test.data" data having a structure of Model class, you can cast that class.

Parse JSON using Newtonsoft.Json C# [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have the following json string:
{
"data":
{
"id": "1",
"city": "London"
},
"cityDetails":
{
"_id": "1",
"location": "UK",
"th": 0,
"title": "Default Group",
}
},
"limit": 0.60451203584671021,
"_id": "1234"
}
How can I extract the the 'city' name from the 'data' section of the JSON string using Newtonsoft.Json in C#.
Try
// load your json here
var obj = JObject.Parse(#"{
""data"":
{
""id"": ""1"",
""city"": ""London""
},
""_id"": ""1234""
}");
// get the city
var city = (string)obj.SelectToken("data.city");
You need to update the selected-token path if the JSON you provided is part of/inside another.

Last entry in dictionary overwrites first written entry when adding dictionary to json file [duplicate]

This question already has an answer here:
Adding object to JArray overwriting first element
(1 answer)
Closed 4 years ago.
I have an existing json file which looks like this:
{
"players": [],
"games": []
}
I want to add objects to the players array so it looks like this:
{
"players": [
{
"name": "Peter",
"checksum": "6fa95b1427af77b3d769ae9cb853382f"
},
{
"name": "John",
"checksum": "61409aa1fd47d4a5332de23cbf59a36f"
},
{
"name": "Bob",
"checksum": "2fc1c0beb992cd7096975cfebf9d5c3b"
}
],
"games": []
}
Players are stored in a global Dictionary<string, string>. But in my implementation, the next element in the dictionary overwrites the first written element so when the loop is at John the next element would be Bob and then Peter gets replaced by Bob. The result of this looks like this:
{
"players": [
{
"name": "Bob",
"checksum": "2fc1c0beb992cd7096975cfebf9d5c3b"
},
{
"name": "John",
"checksum": "61409aa1fd47d4a5332de23cbf59a36f"
},
{
"name": "Bob",
"checksum": "2fc1c0beb992cd7096975cfebf9d5c3b"
}
],
"games": []
}
This is my code:
string json = File.ReadAllText("file.json");
JObject jsonObject = JObject.Parse(json);
JArray jsonPlayerArray = (JArray) jsonObject["players"];
JObject newPlayerEntry = new JObject();
var sortedDict = PlayerChecksumDict.OrderBy(x => x.Key);
foreach (var item in sortedDict)
{
newPlayerEntry["name"] = item.Key;
newPlayerEntry["checksum"] = item.Value;
jsonPlayerArray.Add(newPlayerEntry);
}
string modifiedJson = jsonObject.ToString(Formatting.Indented);
File.WriteAllText("file-modified.json", modifiedJson);
(Similar questions to this have been asked several times, but I haven't been able to find a duplicate, so I figure it's worth answering instead.)
You're creating a single JObject instance, then modifying it multiple times within your loop. Each iteration will overwrite the data set in the previous iteration. Your JArray ends up with lots of references to the same JObject.
Instead, you need to create a new JObject for each entry in your dictionary. To do this, you just need to move the declaration of newPlayerEntry into the loop:
var sortedDict = PlayerChecksumDict.OrderBy(x => x.Key);
foreach (var item in sortedDict)
{
JObject newPlayerEntry = new JObject();
newPlayerEntry["name"] = item.Key;
newPlayerEntry["checksum"] = item.Value;
jsonPlayerArray.Add(newPlayerEntry);
}
Now each element in the JArray will be a reference to a different JObject.

Json.net dynamic brackets without name [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Can you create brackets using dynamic json without the name of the list/array appearing in the json string? Otherwise I will need to rewrite entire section.
The problem is i haven't figured out how to create brackets in dymanic json without having a name that comes before it. In my json string, values will have a parent bracket wrapping all its entries, then a bracket wrapping the timestamp and another bracket wrapping the books. The brackets wrapping timestamp & books should not have names appearing in front of them.
Using this link, I got very close to the format I want but I'm missing the bracket separation for time and the remaining entries.
sample code:
JObject jsonobject = new JObject();
JObject jsonobject2 = new JObject();
dynamic topObject = jsonobject;
topObject.records = new JArray() as dynamic;
dynamic midObject = jsonobject2;
midObject.value = new JArray() as dynamic;
dynamic record = new JObject();
record.TIMESTAMP = DateTime.Now.ToString("MMMM dd yyyy HH:mm:ss");
record.ID = "sampleid";
midObject.value.Add(record);
//query for data
//loop through query
// add to record when data found ex:record.author=dr[0].ToString();
// midObject.value.Add(record);
// finished add data from query
topObject.records.Add(midObject);
string jsonstr = topObject.ToString();
current output:
{
"records": [
{
"value": [
{
"TIMESTAMP": "January 03 2017 09:46:15",
"ID": "sampleID"
},
{
"Title": "Book2",
"Author": "author1"
},
{
"Title": "Book1"
"Author": "author1"
"Notes": "testtest"
}
]
}
]
}
desired output:
{
"records": [
{
"value": [
[ ------->bracket wrapping timestamp
{
"TIMESTAMP": "January 03 2017 09:46:15",
"ID": "sampleID"
}
] ------->bracket wrapping timestamp
,
[ ------->bracket wrapping books
{
"Title": "Book2",
"Artist": "artist1"
},
{
"Title": "Book1"
"Artist": "artist1"
"Notes": "testtest"
}
] ------->bracket wrapping books
]
}
]
}
edit: May have oversimplified but books section has 20+ fields. Each json string will only have one timestamp but can have 100's -1,000's of books per request.
edit2: title / clarification on the main question.
As far as I can see, you just need to add another array for all the records:
JObject jsonobject = new JObject();
JObject jsonobject2 = new JObject();
dynamic topObject = jsonobject;
topObject.records = new JArray() as dynamic;
dynamic midObject = jsonobject2;
midObject.value = new JArray() as dynamic;
dynamic arrayrecord = new JArray();
dynamic record = new JObject();
record.TIMESTAMP = DateTime.Now.ToString("MMMM dd yyyy HH:mm:ss");
record.ID = "sampleid";
arrayrecord.Add(record);
midObject.value.Add(arrayrecord);
//query for data
//loop through query
// add to record when data found ex:record.author=dr[0].ToString();
// midObject.value.Add(record);
// finished add data from query
topObject.records.Add(midObject);
string jsonstr = topObject.ToString();

How to parse a JSON array using C# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Already checked this post but that did not solve my situation : Parsing a JSON array using Json.Net
I have a API response which returns me a JSON array, like the following :
{
"status": {
"code": "200",
"description": "OK"
},
"response": [{
"weId": "1",
"weName": "env1"
},{
"weId": "2",
"weName": "env2"
},{
"weId": "3",
"weName": "env3"
}]
}
Here's my question :
This array might return more than 2 values.
What i mean is like this :
{
"response": [{
"weId": "1",
"weName": "env1",
"otherAttribute1": "otherValue1",
"otherAttribute2": "otherValue2",
"otherAttribute3": "otherValue3"
}]
}
How am I able to dynamically parse a JSON array, which has an unknown dimension ?
Thanks in advance.
Json.Net can dynamically parse into a JObject.
var unParsed = #"{
""response"": [{
""weId"": ""1"",
""weName"": ""env1"",
""otherAttribute1"": ""otherValue1"",
""otherAttribute2"": ""otherValue2"",
""otherAttribute3"": ""otherValue3""
}]
}";
dynamic d = JObject.Parse(unParsed);
Console.WriteLine(d.response[0].weId);
Console.WriteLine(d.response[0].otherAttribute1);
foreach (var r in d.response)
{
foreach (var prop in r.Properties())
{
Console.WriteLine("{0} - {1}", prop.Name, prop.Value);
}
}
Now, that being said, you may not need to do it dynamically. If you have a known set of optional parameters, you can deserialize it into a strongly typed object and anything missing will just be the default value (0 for ints, null for classes, etc), as in the answer below:
public static void JsonParsing()
{
var unParsed = #"{
""status"": {
""code"": ""200"",
""description"": ""OK""
},
""response"": [{
""weId"": ""1"",
""weName"": ""env1""
},{
""weId"": ""2"",
""weName"": ""env2"",
""otherAttribute1"": ""value1"",
""otherAttribute2"": ""value2"",
""otherAttribute3"": ""value3""
},{
""weId"": ""3"",
""weName"": ""env3""
}]
}";
var parsed = JsonConvert.DeserializeObject<Rootobject>(unParsed);
Console.WriteLine(parsed.Response[0].OtherAttribute1); // writes a "" since it's null
Console.WriteLine(parsed.Response[1].OtherAttribute1); // writes "Value1"
Console.WriteLine(parsed);
}

Categories