Fetch values from a JSON response in c# - c#

I have a following JSON repsonse from a API.
"{\"status\":\"True\", \"itemID\":\"201\"}".
On client side, how do I get values from status and itemID.
I am NOT working in javascript. This is a c# class.

Use library to work with json. For example, JSON.NET
Here is example:
string json = #"{
""Name"": ""Apple"",
""Expiry"": new Date(1230422400000),
""Price"": 3.99,
""Sizes"": [
""Small"",
""Medium"",
""Large""
]
}";
JObject o = JObject.Parse(json);
string name = (string)o["Name"];
// Apple
JArray sizes = (JArray)o["Sizes"];
string smallest = (string)sizes[0];
// Small

Take a look at this nifty C# 4.0 implementation http://www.drowningintechnicaldebt.com/ShawnWeisfeld/archive/2010/08/22/using-c-4.0-and-dynamic-to-parse-json.aspx

Related

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

Can I use .NET Newtonsoft JSON package (with or without Linq) to deserialize this oddly formatted JSON response?

I receive this JSON response (but I'm not even sure if this is valid JSON. is it?):
"{\"fields\":\"Name,ParentName,Description,StartDate,EndDate,StartMinute,EndMinute\",\"pos\":0,\"start\":0,\"totalRecords\":1001881,\"data\":[[null,\"AAEC 3400 76142\",null,\"2014-05-15T00:00:00\",\"2014-05-15T00:00:00\",840,1050],[null,\"AAEC 3400 76142\",null,\"2014-05-28T00:00:00\",\"2014-05-28T00:00:00\",840,1050],[null,\"ACCT 5400 25030\",null,\"2014-01-08T00:00:00\",\"2014-01-08T00:00:00\",1215,1290],[null,\"ACCT 5400 25030\",null,\"2014-02-19T00:00:00\",\"2014-02-19T00:00:00\",1215,1290]]}"
Is it possible to deserialize this response and access particular values using Newtonsoft JSON package, with or without the LINQ namespace? Can I access specific values from the "data" key?
Currently, my approach is to manipulate this JSON response into regular JSON, so instead of just having a "fields" key and a "data" key followed by lists of values, I end up deserializing normal JSON key/value pairs (like "Name":"null", "ParentName":"AAEC 3400 76142\", . . . ). Then I can access each object in the list's values by key.
But is it possible to access specific values keeping the response the way it came, without parsing/manipulating it, using Newtonsoft JSON package with/without methods in LINQ namespace?
This is how I'm deserializing the json string that I parse/manipulated manually into normal JSON:
var myList = JsonConvert.DeserializeObject<List<MyClass>>(json);
Then I can access values by key off of specific objects in the response by index:
String name = myList[0].Name;
But can I access the value of myList[0].Name without reformatting the JSON response into typical key:value pairs? Does Newtonsoft provide a way to access the value I want from the response the way it came?
Looks like that JSON has been double-serialized. I.e. some class was serialized as a JSON string, then that string was serialized as JSON again, causing JSON control characters including {,} and " characters to be escaped.
This is almost certainly a bug on the server side, you should try to get it fixed there. But if you cannot (for political reasons, say), you can check for this and work around it on the client side:
var token = JToken.Parse(json);
if (token.Type == JTokenType.String)
token = JToken.Parse((string)token);
var myList = token.ToObject<List<MyClass>>();
Update: your root JSON container is an object, not an array, so ToObject<List<MyClass>> won't work. The unwrapped JSON looks like:
{
"fields": "Name,ParentName,Description,StartDate,EndDate,StartMinute,EndMinute",
"pos": 0,
"start": 0,
"totalRecords": 1001881,
"data": [
[
null,
"AAEC 3400 76142",
null,
"2014-05-15T00:00:00",
"2014-05-15T00:00:00",
840,
1050
],
// More of the same
]
}
If you wanted to reformat that into a more traditional array of JSON objects, you could restructure your root JToken like so:
var token = JToken.Parse(json);
if (token.Type == JTokenType.String)
token = JToken.Parse((string)token);
var fields = (string)token.SelectToken("fields");
var fieldList = fields.Split(',');
var root = new JArray();
root.Add(token.SelectTokens("data[*]").OfType<JArray>().Select(a => new JObject(a.Zip(fieldList, (t, s) => new JProperty(s, t)))));
Debug.WriteLine(root);
With the result:
[
{
"Name": null,
"ParentName": "AAEC 3400 76142",
"Description": null,
"StartDate": "2014-05-15T00:00:00",
"EndDate": "2014-05-15T00:00:00",
"StartMinute": 840,
"EndMinute": 1050
},
// More of the same
]
Yes. It is straightforward and simple to deserialize a JSON response formatted in this way using the Newtonsoft JSON package with LINQ namespace. You don't have to manipulate the response string by hand. Set the JSON response string to a string object named "response", use JObject.Parse() to create a dynamic object "jobject", then you can access the "data" JSON key and set it to a JArray object. Then you can loop through each JToken in "jArray". Finally, get the values by their index in the JArray:
dynamic jobject = JObject.Parse(response);
JArray jArray = jobject.data;
foreach (JToken appointment in jArray)
{
parentName = appointment[1];
startMinute = appointment[5];
. . .
}

How to parse JSON array of string arrays

Lets say I get the following json data from a web service which I can't change.
[
[
"Header1",
"Header2",
"Header3",
"Header4"
],
[
"FirstValue1",
"FirstValue2",
"FirstValue3",
"FirstValue4"
],
[
"SecondValue1",
"SecondValue2",
"SecondValue3",
"SecondValue4"
]
]
jsonlint.com tells me that it is valid json and from what I know I would agree.
But somehow I'm wondering is there any "easy" way to deserialize this to a class. Each of the values in the second and third array belongs to the corresponding header in the first array.
I know how to use Json.NET but can't get my head around on how to use it with this data structure.
Simple - you can use JsonConvert.DeserializeObject to deserialize it to a string[][]:
using System;
using System.IO;
using Newtonsoft.Json;
class Test
{
static void Main()
{
var json = File.ReadAllText("test.json");
string[][] array = JsonConvert.DeserializeObject<string[][]>(json);
Console.WriteLine(array[1][3]); // FirstValue4
}
}
The easiest way is to use the string class and deserialzie it using Json.NET.
string[][] values = JsonConvert.DeserializeObject<string[][]>(json);
A better option could be to use
using Newtonsoft.Json.Linq
string json = #"{
CPU: 'Intel',
Drives: [
'DVD read/writer',
'500 gigabyte hard drive'
]
}";
JObject o = JObject.Parse(json);
string CPU = o.CPU;
int NumDrives = o.Drives.Count;
Source: http://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_Linq_JObject_Parse.htm

C# - JObject.Parse - Invalid JSON

I'm working with an API that is returning JSON.
I have a method that calls the api, and parses the JSON response for the desired nodes.
Up to this point everything has been working fine, except the latest JSON response appears to be malformed.
Other responses come back like:
{
"Keyword":"\"marhope\"",
"TermKey":null,
"Customers":[
{
"Memberships":[ ],
"CompanyId":0,
"ObjectId":112974,
"ObjectType":"Customer",
}
]
}
I use JObject.Parse to bring back the appropriate nodes by name.
The latest JSON response comes back as:
{
[
{
"AnimalId":9079117,
"SpeciesCode":"XX",
}
]
}
As you can see, there is no "name", and the JSON is slightly invalid.
How can I parse this. For the first example I was using the code below, but now that the JSON has no "name", I don't know how to approach this, thoughts?
JObject results = JObject.Parse(csr.SearchCustomer(1, 1, 870, term));
foreach (var resp in results["Customers"])
{
string obj = (string)resp["CompanyId"];
}
Jon Skeet is correct, the second JSON is invalid: you cannot have an array directly inside an object with no property name. The best course of action is to get the API developers to fix the JSON. However, if you're just looking for a quick and dirty workaround, you could strip off the the first and last brace from the invalid JSON and then parse it as an array using JArray.Parse.
string json = #"{
[
{
""AnimalId"":9079117,
""SpeciesCode"":""XX"",
}
]
}";
json = json.Substring(1, json.Length - 2);
JArray array = JArray.Parse(json);
foreach (JObject item in array.Children<JObject>())
{
Console.WriteLine("AnimalId: " + item["AnimalId"]);
Console.WriteLine("SpeciesCode: " + item["SpeciesCode"]);
}

Deserialize a Dynamic JSON Array on C# WebForm

Hi I am generating a JSON on my API that I am trying to use on codebehind C# in my web application but I cannot deserialize well.
My JSON has an object with JSON arrays and the element inside the array are dynamic so I cannot create a fixed class with those items becuase my JSON can have N ITEMS.
{
"MAINOBJET": [{
"ITEM1": "23800",
"ITEM2": "Dahl; Police",
"ITEM3": "test#test.net"
},
{
"ITEM1": "23802",
"ITEM2": "Steve ; Police",
"ITEM3": "test2#test.net"
}]
}
So how can I deserialize it to a DataTable, list or a Dictionary?
Thank you
here you can do some thing like the following this example should be able to get you started .. replace the structure / example with your Jason Text
lets say that my JSON Script looks like the following
{
"some_number": 253.541,
"date_time": "2012-26-12T11:53:09Z",
"serial_number": "SN8675309"
"more_data": {
"field1": 1.0
"field2": "hello JSON Deserializer"
}
}
assign you JSON jsonText to a variable and pass it to the following C# Code
using System.Web.Script.Serialization;
var jsonSerialization = new JavaScriptSerializer();
var dictObj = jsonSerialization.Deserialize<Dictionary<string,dynamic>>(jsonText);
Console.WriteLine(dictObj["some_number"]); //outputs 253.541
Console.WriteLine(dictObj["more_data"]["field2"]); //outputs hello JSON Deserializer

Categories