JObject Not Parsing Values I need - c#

String Contents =
{
"links":[
{
".tag":"file",
"url":"myURL",
"id":"CCCCC",
"name":"CCCC",
"path_lower":"CCCC"
},
{
"url".. and so on.
}
JObject json = JObject.Parse(contents);
Console.WriteLine(json.GetValue("links.url"));
I am trying to get all the URL values and store them into an array. The problem is that this code does not parse anything.
The main json is links and the rest is under it. How can I go about getting all the URL values?

Take json["links"] as JArray.
Use Linq to retrieve url from the element in (1) and cast it to string.
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.Linq;
JObject json = JObject.Parse(contents);
JArray array = json["links"] as JArray;
List<string> links = array.Select(x => (string)x["url"]).ToList();
Sample demo on .NET Fiddle

Related

Moving all properties from a nested JObject to the root

I have the following json format that I need to change by removing the "root" element and then sending it for processing.
{
"deonItemDetails":[
{
"hsDesc":"",
"namePLU":"AGO LOCAL",
"taxRate":0.0,
"unitPrice":71.0,
"discount":0.0,
"hsCode":"",
"quantity":1.0,
"measureUnit":"Litres",
"vatClass":"A"
}
],
"root":{
"senderId":"a4031de9-d11f-4b52-8cca-e1c7422f3c37",
"invoiceCategory":"tax_invoice",
"traderSystemInvoiceNumber":"34058",
"relevantInvoiceNumber":"",
"pinOfBuyer":"P051400323I",
"invoiceType":"Original",
"exemptionNumber":"",
"totalInvoiceAmount":71.0,
"systemUser":"manager"
}
}
I need it to be like this:
{
"deonItemDetails":[
{
"hsDesc":"",
"namePLU":"AGO LOCAL",
"taxRate":0.0,
"unitPrice":71.0,
"discount":0.0,
"hsCode":"",
"quantity":1.0,
"measureUnit":"Litres",
"vatClass":"A"
}
],
"senderId":"a4031de9-d11f-4b52-8cca-e1c7422f3c37",
"invoiceCategory":"tax_invoice",
"traderSystemInvoiceNumber":"34058",
"relevantInvoiceNumber":"",
"pinOfBuyer":"P051400323I",
"invoiceType":"Original",
"exemptionNumber":"",
"totalInvoiceAmount":71.0,
"systemUser":"manager"
}
However, using the following code, all content of root is removed instead of just the tag and brackets belinging to that node.
JObject jo = JObject.Parse(jsonToSendDetails);
jo.Property("root").Remove();
var newjson = jo.ToString();
How do I get the json to look like the 2nd one?
Solution 1
#JonSkeet had explained the concept:
Get the properties in the root.
Add the properties from 1 to the JObject.
Remove the root property from the JObject.
The below code is the implementation:
using Newtonsoft.Json.Linq;
JObject jObj = JObject.Parse(json);
JObject rootObj = (JObject)jObj["root"];
foreach (JProperty prop in rootObj.Properties())
{
jObj.Add(prop.Name, prop.Value);
}
jObj.Remove("root");
Demo Solution 1 # .Net Fiddle
Solution 2
Besides, you may work with JObject.Merge() as well.
using Newtonsoft.Json.Linq;
JObject jObj = JObject.Parse(json);
jObj.Merge(jObj["root"]);
jObj.Remove("root");
Demo Solution 2 # .NET Fiddle
just for the record
var jsonParsed = JObject.Parse(json);
var fixedObj = (JObject)jsonParsed["root"];
//if, most probably, the order of properties doesn't matter
fixedObj["deonItemDetails"] = jsonParsed["deonItemDetails"];
json = fixedObj.ToString();
// or if the order of properties matters
fixedObj.AddFirst( new JProperty("deonItemDetails", jsonParsed["deonItemDetails"]));

Deserializing JSON response without creating a class

From the result of an API call I have a large amount of JSON to process.
I currently have this
Object convertObj = JsonConvert.DeserializeObject(responseFromServer);
I am aware that I could do something like
Movie m = JsonConvert.DeserializeObject<Movie>(responseFromServer);
And then use it like
m.FieldName
m.AnotherField
//etc
Ideally I would like to do something like
var itemName = convertObj["Name"];
to get the first Name value for the first item in the list.
Is this possible, or do I have to create a class to deserialize to?
The reason I do not want to create the class is I am not the owner of the API and the field structure may change.
Edit.
Okay so I created the class as it seems the best approach, but is there a way to deserialize the JSON into a list?
var sessionScans = new List<SessionScan>();
sessionScans = JsonConvert.DeserializeObject<SessionScan>(responseFromServer);
Complains that it cannot convert SessionScan to generic list.
No need to use dynamic, you can simply use JToken which is already does what you expect:
var json = #"
{
""someObj"": 5
}
";
var result = JsonConvert.DeserializeObject<JToken>(json);
var t = result["someObj"]; //contains 5
With .NET 6, this can be done as below,
using System.Text.Json;
using System.Text.Json.Nodes;
string jsonString = #"some json string here";
JsonNode forecastNode = JsonNode.Parse(jsonString)!;
int temperatureInt = (int)forecastNode!["Temperature"]!;
Console.WriteLine($"Value={temperatureInt}");
//for nested elements, you can access as below
int someVal = someNode!["someParent"]["childId"]!.ToString();
Refer this MS docs page for more samples - create object using initializers, make changes to DOM, deserialize subsection of a JSON payload.
You can try with JObject.Parse :
dynamic convertObj = JObject.Parse("{ 'Name': 'Jon Smith', 'Address': { 'City': 'New York', 'State': 'NY' }, 'Age': 42 }");
string name = convertObj.Name;
string address = convertObj.Address.City;
The below example can deserialize JSON to a list of anonymous objects using NewtonSoft.Json's DeserializeAnonymousType method.
var json = System.IO.File.ReadAllText(#"C:\TestJSONFiles\yourJSONFile.json");
var fooDefinition = new { FieldName = "", AnotherField = 0 }; // type with fields of string, int
var fooListDefinition = new []{ fooDefinition }.ToList();
var foos = JsonConvert.DeserializeAnonymousType(json, fooListDefinition);
You can use Json.NET's LINQ to JSON API
JObject o = JObject.Parse(jsonString);
string prop = (string)o["prop"];
Use Newtonsoft.Json
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
var json = "[{'a':'aaa','b':'bbb','c':'ccc'},{'a':'aa','b':'bb','c':'cc'}]";
var ja = (JArray)JsonConvert.DeserializeObject(json);
var jo = (JObject) ja[0];
Console.WriteLine(jo["a"]);
I had this problem working with unknown APIs then I decide to come over this problem using this approach, I'm writing down here my test case:
[TestMethod]
public void JsonDocumentDeserialize()
{
string jsonResult = #"{
""status"": ""INTERNAL_SERVER_ERROR"",
""timestamp"": ""09-09-2019 11:00:24"",
""message"": ""documentUri is required.""
}";
var jDoc = JsonDocument.Parse(jsonResult);
if (jDoc.RootElement.TryGetProperty("message", out JsonElement message))
{
Assert.IsTrue(message.GetString() == "documentUri is required.");
}
}
it worked for me because first I was looking to find a way to use dynamic type as it's mentioned in Azure Function HTTPTrigger. But I found this approach most useful and robust.
Microsoft Reference

Check if user is on list

I have Array in JSON file. File looks like this:
["Maverick", "rick", "Rick", "prick", "rick_07"]
I have a username. I want to check if this username is in Array.
public string UserToCheck = "rick";
So im reading json file from URL...
using (var webClient = new System.Net.WebClient())
{
var json = webClient.DownloadString("http://example.ex/users.json");
// Here I want to check if user is on list
}
}
But how Can I check if "UserToCheck" exactly match one of users from array?
You could parse your Json with the great Newtonsoft Json Library:
var users = JsonConvert.DeserializeObject<List<string>>(json);
users.Contains(UserToCheck);
As this is case sensitive, you could use LINQ: users.Any(u => String.Equals(u, UserToCheck, StringComparison.OrdinalIgnoreCase))
Trying parsing the object using JSON parsing. This requires placing the JSON string object into JSON.Parse method.
This portion may be missing:
JObject jObj = JObject.Parse(json);
Console.WriteLine(jObj);
Helpful links: http://www.newtonsoft.com/json/help/html/ParseJsonObject.htm
http://masnun.com/2011/07/08/quick-json-parsing-with-c-sharp.html
To check the string for names, break the names up into a list with C# and iterate through that to check the results.

Deserialize a json string in specific format

I am trying to deserialize the JSON string below:
[{"Code1":"AA","Code2":"AB"},{"Code1":"BB","Code2":"BC"},
{"Code1":"A1","Code2":"A12"},{"Code1":"A2","Code2":"A23"},
{"Code1":"A4","Code2":"A45"},{"Code1":"A3","COde2":"A45"}]
into the following format:
{"Header":["Code1","Code2"], "Values":[["AA","AB"],["BB","BC"],["A1","A12"],["A2","A23"],["A4","A45"],["A3","A45"]]}
I am trying to deserialize using JsonConvert.DeseriaizeObject(). I am not able to achieve the desired format.
Ah, so you have a collection of identically structured objects, and want to convert it to something akin to a CSV table (sequence of headers, then sequence of records)?
You can convert from the objects collection format to records table format using the following method:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
//other code, class declaration etc. goes here
string ObjectsToTable(string collectionJson)
{
// reading the collection from passed JSON string
JArray collection = JArray.Parse(collectionJson);
// retrieving header as a list of properties from the first element
// it is assumed all other elements have the exact same properties
List<string> header = (collection.First as JObject).Properties().Select(p => p.Name).ToList();
// retrieving values as lists of strings
// each string is corresponding to the property named in the header
List<List<string>> values = collection.Children<JObject>().Select( o => header.Select(p => o[p].ToString()).ToList() ).ToList();
// passing the table structure with the header and values
return JsonConvert.SerializeObject(new { Header = header, Values = values });
}

SimpleJson in WP8

I am trying to parse a json file in WP8. For the moment I just need to get a list of topics with some titles each one. Something like:
[
{"topic":"topic1",
"titles":[{"title":"tit1"},
{"title":"tit2"},
{"title":"tit3"}]},
{"topic":"topic1",
"titles":[{"title":"tit1"},
{"title":"tit2"},
{"title":"tit3"}]}
]
My idea is get each topic and save in an array of 2 dimensions. In topic[X][0] would go topic and topic[x][y] the titles...
I have found this topic: Deserializing JSON using JSon.NET with dynamic data
In which is explained a bit how to do it but I am not able to get any of my data because the structure of the json is not similar. Any idea of how to do in this case?
To parse just call:
JArray json = JsonConvert.DeserializeObject(jsonText) as JArray;
For getting the topics just access it normally:
JObject arrayItem = json[0] as JObject;
Getting the topic and it's value:
JValue topic = arrayItem["topic"] as JValue;
string topicValue = topic.Value.ToString();
Getting the titles:
JArray titles = ArrayItem["titles"] as JArray;
And getting their values:
foreach (JObject jo in titles)
{
JValue title = jo["title"] as JValue;
string titleValue = title.Value.ToString();
}

Categories