Parse dynamic json as simple as possible - c#

I am not much of a C# Programmer so I am fairly new to this, I would like to parse the sample JSON below, I have been using the code:
WebClient client = new WebClient();
string getString = client.DownloadString(url);
dynamic j = JsonConvert.DeserializeObject(getString);
var k = j.rgDescriptions;
dynamic m = JsonConvert.DeserializeObject(k);
foreach (var c in m.descriptions)
{
Console.WriteLine(c);
}
I get error in deserialize of k, I am not sure if I am at the right path though. How do I get the "classid" w/o getting the value of their parent, because it is dynamic and not named, it is a Unique ID.
{
"success": true,
"rgDescriptions": {
"671219543": {
"id": "671219543",
"classid": "253033065",
"instanceid": "93973071",
"amount": "1",
"pos": 274
},
"707030894": {
"id": "707030894",
"classid": "166354998",
"instanceid": "0",
"amount": "1",
"pos": 277
},
Update:
I used this code:
WebClient client = new WebClient();
string getString = client.DownloadString(url);
var jo = JObject.Parse(getString);
var data = (JObject)jo["rgDescriptions"];
foreach (var item in data)
{
Console.WriteLine("{0}: {1}", item.Key, item.Value);
}
I could get what I wanted now, but I need to parse each value. Is there a better way?

You could use JSON.NET and JSONPath to query the incoming JSON, examples here and here
The code below extracts every classid for each object in rgDescriptions
//...
WebClient client = new WebClient();
string getString = client.DownloadString(url);
var obj = JObject.Parse(getString);
var classIds = obj.SelectTokens("$.rgDescriptions.*.classid").Select(x => x.Value<string>()).ToList(); //[253033065,166354998]
//Class ID Where...
var idToSearch = "671219543";
var classId = obj.SelectToken("$.rgDescriptions['" + idToSearch + "']..classid").Value<string>();
//...

Related

C# Deserialize string of multiple arrays with json-string in it explicit to List<string>

i have a json-string, or bit more something like a "string of arrays":
"[
{
"type":"radio-group",
"label":"Radio-Button-Gruppe",
"name":"radio-group-1556028993486",
"className":"iCheck",
"values":[
{
"label":"aaaaaaa",
"value":"aaaaaaa"
},
{
"label":"bbbbbbbbb",
"value":"bbbbbbbbb"
},
{
"label":"cccccccccccc",
"value":"cccccccccccc"
}
]
}
],
[
...
],
[
{
"type":"header",
"label":"Überschrift"
}
]"
Now I want to have a List<string> of each array in this string. Something like:
List<string> x[0] = "{
"type":"radio-group",
"label":"Radio-Button-Gruppe",
"name":"radio-group-1556028993486",
"className":"iCheck",
"values":[
{
"label":"aaaaaaa",
"value":"aaaaaaa"
},
{
"label":"bbbbbbbbb",
"value":"bbbbbbbbb"
},
{
"label":"cccccccccccc",
"value":"cccccccccccc"
}
]
}"
What's the best way to do that?
I already tried out JsonConvert.DeserializeObject<IEnumerable<string>>() but my problem is that he wants to deserialize my jsons to an object. But I want to keep them as a string und put them to my list.
Why I need a list of string for each array?
Because I use the json-strings inside the arrays to render a form. each array show you a page of the form, and the json is the data for rendering this form.
to render this form i have to go through a loop through all of this arrays and render the json in it for every page.
You can use JsonConvert.DeserializeObject<IEnumerable<JToken>>(json) where json is each of your top level arrays. Then you can iterate through the results and use .ToString() on each JToken object.
As others have pointed out, you don't have valid JSON, so I didn't try to give a solution to parse out the top level arrays.
var json = #"[
{
""type"":""radio-group"",
""label"":""Radio-Button-Gruppe"",
""name"":""radio-group-1556028993486"",
""className"":""iCheck"",
""values"":[
{
""label"":""aaaaaaa"",
""value"":""aaaaaaa""
},
{
""label"":""bbbbbbbbb"",
""value"":""bbbbbbbbb""
},
{
""label"":""cccccccccccc"",
""value"":""cccccccccccc""
}
]
}
]";
var arrays = new[] { json };
var objectsAsStrings = new List<string>();
foreach (var array in arrays)
{
var tokens = JsonConvert.DeserializeObject<IEnumerable<JToken>>(array);
foreach (var token in tokens)
{
objectsAsStrings.Add(token.ToString());
}
}
var json = "yourjson";
var jsonnew = "[" + json+ "]";
var list = JsonConvert.DeserializeObject<dynamic>(jsonnew);
var result = new List<string>();
foreach (var item in list)
{
var str = JsonConvert.SerializeObject(item);
result.Add(str);
}
You can use this , too.

csv to json file format

I want to convert my csv file into .json format using c#. here what i have tried:
var lines = #"text,intentName,entityLabels
1,2,null
2,1,null".Replace("\r", "").Split('\n');
var csv = lines.Select(l => l.Split(',')).ToList();
var headers = csv[0];
var dicts = csv.Skip(1).Select(row => Enumerable.Zip(headers, row,
Tuple.Create).ToDictionary(p => p.Item1, p => p.Item2)).ToArray();
string json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(dicts);
Result1.Text = json;
The result is :
[
{
"text":" 1",
"intentName":"2",
"entityLabels":"null"
},
{
"text":"2",
"intentName":"1",
"entityLabels":"null"
}
]
it almost like I expected, however I want to make if the entityLabels column is null, then it replace into []. so the output that I expecting is:
[
{
"text":" 1",
"intentName":"2",
"entityLabels":[]
},
{
"text":"2",
"intentName":"1",
"entityLabels":[]
}
]
anyone know how to do it?
With external lib Cinchoo ETL - an open source library, you can convert CSV --> JSON with the expected format as below
Method 1:
string csv = #"text,intentName,entityLabels
1,2,null
2,1,null
";
StringBuilder sb = new StringBuilder();
using (var p = ChoCSVReader.LoadText(csv)
.WithFirstLineHeader()
.WithField("text")
.WithField("intentName")
.WithField("entityLabels", fieldType: typeof(int[]), nullValue: "null")
)
{
using (var w = new ChoJSONWriter(sb)
)
w.Write(p);
}
Console.WriteLine(sb.ToString());
Sample fiddle: https://dotnetfiddle.net/5M7fFX
Method 2:
string csv = #"text,intentName,entityLabels
1,2,null
2,1,null
";
StringBuilder sb = new StringBuilder();
using (var p = ChoCSVReader.LoadText(csv)
.WithFirstLineHeader()
.WithField("text")
.WithField("intentName")
.WithField("entityLabels", valueConverter: (o) => new int[] { })
)
{
using (var w = new ChoJSONWriter(sb)
)
w.Write(p);
}
Console.WriteLine(sb.ToString());
Sample fiddle: https://dotnetfiddle.net/gOX3FJ
Output:
[
{
"text": "1",
"intentName": "2",
"entityLabels": []
},
{
"text": "2",
"intentName": "1",
"entityLabels": []
}
]
Hope it helps.
Don't try to use string operations to convert from one data type to another.
Instead use an actual CSV parsing library like csvhelper (available on NuGet) to deserialise the CSV into objects, and then re-serialise that same data as JSON using a JSON serializer.

return array of arrays instead of array of objects with json.net

I need to return an array of arrays instead of an array of objects for a flot chart.
I can get the following:
data = [{"2012-10": 4140},{"2012-11": 10815},{"2012-12": 10444}];
but need (UPDATE fixed following line):
data = [["2012-10", 4140],["2012-11", 10815],["2012-12", 10444]];
Here is the c# which is parsing inbound json from another source:
public async Task<ActionResult> Chart(string custid)
{
//Get the financial results from DRT
var response = await DominoJSON.getJSON(custid, "drtHistory", "DRT");
JArray UOVol = new JArray();
var array = JArray.Parse(response);
foreach (var token in array)
{
JObject o = JObject.Parse(token.ToString());
int uovol = Convert.ToInt32(o["UOVol"]);
string uodate = o.SelectToken("DATE").ToString();
JObject UOItem = new JObject(new JProperty(uodate, uovol));
UOVol.Add(UOItem);
}
string resultUO = UOVol.ToString();
ViewBag.UOData = resultUO;
return View();
}
And the inbound json being parsed:
[
{
"DATE":"2012-10",
"UOVol":4140,
"FIRev":180,
"AFRev":692.75,
"ABRev":2900,
"OWRev":3791.25,
},
{
"DATE":"2012-11",
"UOVol":10815,
"FIRev":60,
"AFRev":170,
"ABRev":0,
"OWRev":3037.5,
},
{
"DATE":"2012-12",
"UOVol":10444,
"FIRev":40,
"AFRev":514.25,
"ABRev":1450,
"OWRev":7500,
}
]
I can't figure out how to turn the JObjects to arrays. I have tried this with other approaches including using a dictionary and list. Any help or alternate solutions would be helpful. Using VS2013, mvc 5 and EF 6.
Try this:
class Program
{
static void Main(string[] args)
{
string jsonIn = #"
[
{
""DATE"": ""2012-10"",
""UOVol"": 4140,
""FIRev"": 180,
""AFRev"": 692.75,
""ABRev"": 2900,
""OWRev"": 3791.25
},
{
""DATE"": ""2012-11"",
""UOVol"": 10815,
""FIRev"": 60,
""AFRev"": 170,
""ABRev"": 0,
""OWRev"": 3037.5
},
{
""DATE"": ""2012-12"",
""UOVol"": 10444,
""FIRev"": 40,
""AFRev"": 514.25,
""ABRev"": 1450,
""OWRev"": 7500
}
]";
JArray arrayIn = JArray.Parse(jsonIn);
JArray arrayOut = new JArray();
foreach (JObject jo in arrayIn.Children<JObject>())
{
JArray ja = new JArray();
ja.Add(jo["DATE"]);
ja.Add(jo["UOVol"]);
arrayOut.Add(ja);
}
string jsonOut = arrayOut.ToString(Formatting.None);
Console.WriteLine(jsonOut);
}
}
Output:
[["2012-10",4140],["2012-11",10815],["2012-12",10444]]

Parsing a JSON array using Json.Net

I'm working with Json.Net to parse an array. What I'm trying to do is to pull the name/value pairs out of the array and assign them to specific variables while parsing the JObject.
Here's what I've got in the array:
[
{
"General": "At this time we do not have any frequent support requests."
},
{
"Support": "For support inquires, please see our support page."
}
]
And here's what I've got in the C#:
WebRequest objRequest = HttpWebRequest.Create(dest);
WebResponse objResponse = objRequest.GetResponse();
using (StreamReader reader = new StreamReader(objResponse.GetResponseStream()))
{
string json = reader.ReadToEnd();
JArray a = JArray.Parse(json);
//Here's where I'm stumped
}
I'm fairly new to JSON and Json.Net, so it might be a basic solution for someone else. I basically just need to assign the name/value pairs in a foreach loop so that I can output the data on the front-end. Has anyone done this before?
You can get at the data values like this:
string json = #"
[
{ ""General"" : ""At this time we do not have any frequent support requests."" },
{ ""Support"" : ""For support inquires, please see our support page."" }
]";
JArray a = JArray.Parse(json);
foreach (JObject o in a.Children<JObject>())
{
foreach (JProperty p in o.Properties())
{
string name = p.Name;
string value = (string)p.Value;
Console.WriteLine(name + " -- " + value);
}
}
Fiddle: https://dotnetfiddle.net/uox4Vt
Use Manatee.Json
https://github.com/gregsdennis/Manatee.Json/wiki/Usage
And you can convert the entire object to a string, filename.json is expected to be located in documents folder.
var text = File.ReadAllText("filename.json");
var json = JsonValue.Parse(text);
while (JsonValue.Null != null)
{
Console.WriteLine(json.ToString());
}
Console.ReadLine();
I know this is about Json.NET but times are a-changing so if anybody stumbles here while using .NET Core/5+ System.Text.Json please don't despair because
Try the new System.Text.Json APIs from .NET Blog show an example of this.
[
{
"date": "2013-01-07T00:00:00Z",
"temp": 23,
},
{
"date": "2013-01-08T00:00:00Z",
"temp": 28,
},
{
"date": "2013-01-14T00:00:00Z",
"temp": 8,
},
]
...
using (JsonDocument document = JsonDocument.Parse(json, options))
{
int sumOfAllTemperatures = 0;
int count = 0;
foreach (JsonElement element in document.RootElement.EnumerateArray())
{
DateTimeOffset date = element.GetProperty("date").GetDateTimeOffset();
(...)

Convert Newtonsoft.Json.Linq.JArray to a list of specific object type

I have the following variable of type {Newtonsoft.Json.Linq.JArray}.
properties["Value"] {[
{
"Name": "Username",
"Selected": true
},
{
"Name": "Password",
"Selected": true
}
]}
What I want to accomplish is to convert this to List<SelectableEnumItem> where SelectableEnumItem is the following type:
public class SelectableEnumItem
{
public string Name { get; set; }
public bool Selected { get; set; }
}
I am rather new to programming and I am not sure whether this is possible. Any help with working example will be greatly appreciated.
Just call array.ToObject<List<SelectableEnumItem>>() method. It will return what you need.
Documentation: Convert JSON to a Type
The example in the question is a simpler case where the property names matched exactly in json and in code. If the property names do not exactly match, e.g. property in json is "first_name": "Mark" and the property in code is FirstName then use the Select method as follows
List<SelectableEnumItem> items = ((JArray)array).Select(x => new SelectableEnumItem
{
FirstName = (string)x["first_name"],
Selected = (bool)x["selected"]
}).ToList();
The API return value in my case as shown here:
{
"pageIndex": 1,
"pageSize": 10,
"totalCount": 1,
"totalPageCount": 1,
"items": [
{
"firstName": "Stephen",
"otherNames": "Ebichondo",
"phoneNumber": "+254721250736",
"gender": 0,
"clientStatus": 0,
"dateOfBirth": "1979-08-16T00:00:00",
"nationalID": "21734397",
"emailAddress": "sebichondo#gmail.com",
"id": 1,
"addedDate": "2018-02-02T00:00:00",
"modifiedDate": "2018-02-02T00:00:00"
}
],
"hasPreviousPage": false,
"hasNextPage": false
}
The conversion of the items array to list of clients was handled as shown here:
if (responseMessage.IsSuccessStatusCode)
{
var responseData = responseMessage.Content.ReadAsStringAsync().Result;
JObject result = JObject.Parse(responseData);
var clientarray = result["items"].Value<JArray>();
List<Client> clients = clientarray.ToObject<List<Client>>();
return View(clients);
}
I can think of different method to achieve the same
IList<SelectableEnumItem> result= array;
or (i had some situation that this one didn't work well)
var result = (List<SelectableEnumItem>) array;
or use linq extension
var result = array.CastTo<List<SelectableEnumItem>>();
or
var result= array.Select(x=> x).ToArray<SelectableEnumItem>();
or more explictly
var result= array.Select(x=> new SelectableEnumItem{FirstName= x.Name, Selected = bool.Parse(x.selected) });
please pay attention in above solution I used dynamic Object
I can think of some more solutions that are combinations of above solutions. but I think it covers almost all available methods out there.
Myself I use the first one
using Newtonsoft.Json.Linq;
using System.Linq;
using System.IO;
using System.Collections.Generic;
public List<string> GetJsonValues(string filePath, string propertyName)
{
List<string> values = new List<string>();
string read = string.Empty;
using (StreamReader r = new StreamReader(filePath))
{
var json = r.ReadToEnd();
var jObj = JObject.Parse(json);
foreach (var j in jObj.Properties())
{
if (j.Name.Equals(propertyName))
{
var value = jObj[j.Name] as JArray;
return values = value.ToObject<List<string>>();
}
}
return values;
}
}
Use IList to get the JArray Count and Use Loop to Convert into List
var array = result["items"].Value<JArray>();
IList collection = (IList)array;
var list = new List<string>();
for (int i = 0; i < collection.Count; j++)
{
list.Add(collection[i].ToString());
}

Categories

Resources