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
Related
I have a JSON body which looks like this(an array of objects):
[
{
"registered": "2016-02-03T07:55:29",
"color": "red",
},
{
"registered": "2016-02-03T17:04:03",
"color": "blue",
}
]
This body is contained in a variable(requestBody) I create based on a HTTP Request, it's called req:
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
What I want to do is add a unique identifier to each one of the objects in my JSON array. How could I go about achieving this?
Currently I am deserializing the JSON, adding some string(x) to it and then serializing it again:
dynamic d = JsonConvert.DeserializeObject(requestBody);
d.uniqueId = "x";
string newBody = JsonConvert.SerializeObject(d);
I was to add a uniqueId to each one of the objects in my JSON array of objects. How could I achieve this?
You can use JArray from LINQ to JSON API to parse, iterate children of JObject type and modify them:
var json = ...; // your json string
var jArray = JArray.Parse(json);
foreach (var jObject in jArray.Children<JObject>())
{
jObject.Add("id", new JValue("x"));
}
var modified = JsonConvert.SerializeObject(jArray);
I have a JSON string from which I want to be able to delete some data.
Below is the JSON response:
{
"ResponseType": "VirtualBill",
"Response": {
"BillHeader": {
"BillId": "7134",
"DocumentId": "MN003_0522060",
"ConversionValue": "1.0000",
"BillType": "Vndr-Actual",
"AccountDescription": "0522060MMMDDYY",
"AccountLastChangeDate": "06/07/2016"
}
},
"Error": null
}
From above JSON response I want to able remove the
"ResponseType": "VirtualBill", part such that it looks like this:
{
"Response": {
"BillHeader": {
"BillId": "7134",
"DocumentId": "MN003_0522060",
"ConversionValue": "1.0000",
"BillType": "Vndr-Actual",
"AccountDescription": "0522060MMMDDYY",
"AccountLastChangeDate": "06/07/2016"
}
},
"Error": null
}
Is there an easy way to do this in C#?
Using Json.Net, you can remove the unwanted property like this:
JObject jo = JObject.Parse(json);
jo.Property("ResponseType").Remove();
json = jo.ToString();
Fiddle: https://dotnetfiddle.net/BgMQAE
If the property you want to remove is nested inside another object, then you just need to navigate to that object using SelectToken and then Remove the unwanted property from there.
For example, let's say that you wanted to remove the ConversionValue property, which is nested inside BillHeader, which is itself nested inside Response. You can do it like this:
JObject jo = JObject.Parse(json);
JObject header = (JObject)jo.SelectToken("Response.BillHeader");
header.Property("ConversionValue").Remove();
json = jo.ToString();
Fiddle: https://dotnetfiddle.net/hTlbrt
Convert it to a JsonObject, remove the key, and convert it back to string.
Sample sample= new Sample();
var properties=sample.GetType().GetProperties().Where(x=>x.Name!="ResponseType");
var response = new Dictionary<string,object>() ;
foreach(var prop in properties)
{
var propname = prop.Name;
response[propname] = prop.GetValue(sample); ;
}
var response= Newtonsoft.Json.JsonConvert.SerializeObject(response);
My question is simple but i can not do that. i wanna get value of "soap:Body" from below string by C#code?
{"soap:Envelope":{"xmlns:xsd":"http://www.w3.org/2001/XMLSchema","xmlns:soap":"http://www.w3.org/2003/05/soap-envelope","xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","soap:Body":{"ToplamaResponse":{"xmlns":"http://tempuri.org/","ToplamaResult":156758}}}}
You can also use the Framework class JavaScriptSerializer if you do not want to use an external library.
string json = #"...";
JavaScriptSerializer serializer = new JavaScriptSerializer();
var o = serializer.Deserialize<dynamic>(json);
var body = o["soap:Envelope"]["soap:Body"];
You can do it easily by using Json.NET
dynamic data = JObject.Parse("{'soap:Envelope':{'xmlns:xsd':'http://www.w3.org/2001/XMLSchema','xmlns:soap':'http://www.w3.org/2003/05/soap-envelope','xmlns:xsi':'http://www.w3.org/2001/XMLSchema-instance','soap:Body':{'ToplamaResponse':{'xmlns':'http://tempuri.org/','ToplamaResult':156758}}}}");
string soap_body = data["soap:Envelope"]["soap:Body"];
There is a simple example in the JObject.Parse documentation
string json = #"{
"soap:Envelope": {
"xmlns:xsd": "http://www.w3.org/2001/XMLSchema",
"xmlns:soap": "http://www.w3.org/2003/05/soap-envelope",
"xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"soap:Body": {
"ToplamaResponse": {
"xmlns": "http://tempuri.org/",
"ToplamaResult": 156758
}
}
}
}";
JObject obj = JObject.Parse(json);
Console.WriteLine((string)obj["soap:Envelope"]["soap:Body"]);
And if you want to manipulate the value of "soap:Body" do the same thing :)
I have this String stored in my database:
str = "{ "context_name": { "lower_bound": "value", "upper_bound": "value", "values": [ "value1", "valueN" ] } }"
This string is already in the JSON format but I want to convert it into a JObject or JSON Object.
JObject json = new JObject();
I tried the json = (JObject)str; cast but it didn't work so how can I do it?
JObject defines method Parse for this:
JObject json = JObject.Parse(str);
You might want to refer to Json.NET documentation.
if you don't want or need a typed object try:
using Newtonsoft.Json;
// ...
dynamic json = JsonConvert.DeserializeObject(str);
or try for a typed object try:
using Newtonsoft.Json;
// single
Foo foo = JsonConvert.DeserializeObject<Foo>(str);
// or as a list
List<Foo> foos = JsonConvert.DeserializeObject<List<Foo>>(str);
This works
string str = "{ 'context_name': { 'lower_bound': 'value', 'pper_bound': 'value', 'values': [ 'value1', 'valueN' ] } }";
JavaScriptSerializer j = new JavaScriptSerializer();
object a = j.Deserialize(str, typeof(object));
there's an interesting way to achive another goal which is to have a strongly type class base on json with a very powerfull tools that i used few days ago for first time to translate tradedoubler json result into classes
Is a simple tool: copy your json source paste and in few second you will have a strongly typed class json oriented .
In this manner you will use these classes which is more powerful and simply to use.
You can try like following:
string output = JsonConvert.SerializeObject(jsonStr);
This works for me using JsonConvert
var result = JsonConvert.DeserializeObject<Class>(responseString);
If your JSon string has "" double quote instead of a single quote ' and has \n as a indicator of a next line then you need to remove it because that's not a proper JSon string, example as shown below:
SomeClass dna = new SomeClass ();
string response = wc.DownloadString(url);
string strRemSlash = response.Replace("\"", "\'");
string strRemNline = strRemSlash.Replace("\n", " ");
// Time to desrialize it to convert it into an object class.
dna = JsonConvert.DeserializeObject<SomeClass>(#strRemNline);
In a situation where you are retrieving a list of objects of a certain entity from your api, your response string may look like this:
[{"id":1,"nome":"eeee","username":null,"email":null},{"id":2,"nome":"eeee","username":null,"email":null},{"id":3,"nome":"Ricardo","username":null,"email":null}]
In this situation you may want an array of Jason objects and cycle through them to populate your c# variable. I've done like so:
var httpResponse = await Http.GetAsync($"api/{entidadeSelecionada}");
List<List<string[]>> Valores = new();
if (httpResponse.IsSuccessStatusCode)
{
//totalPagesQuantity = int.Parse(httpResponse.Headers.GetValues("pagesQuantity").FirstOrDefault());
//Aqui tenho que colocar um try para o caso de ser retornado um objecto vazio
var responseString = await httpResponse.Content.ReadAsStringAsync();
JArray array = JArray.Parse(responseString);
foreach (JObject objx in array.Children<JObject>())
{
List<string[]> ls = new();
foreach (JProperty singleProp in objx.Properties())
{
if (!singleProp.Name.Contains("_xyz"))
{
string[] val = new string[2];
val[0] = singleProp.Name;
val[1] = singleProp.Value.ToString();
ls.Add(val);
}
}
Valores.Add(ls);
}
}
return Valores;
I achieved this solution by the #Andrei answer.
This does't work in case of the JObject this works for the simple json format data. I have tried my data of the below json format data to deserialize in the type but didn't get the response.
For this Json
{
"Customer": {
"id": "Shell",
"Installations": [
{
"id": "Shell.Bangalore",
"Stations": [
{
"id": "Shell.Bangalore.BTM",
"Pumps": [
{
"id": "Shell.Bangalore.BTM.pump1"
},
{
"id": "Shell.Bangalore.BTM.pump2"
},
{
"id": "Shell.Bangalore.BTM.pump3"
}
]
},
{
"id": "Shell.Bangalore.Madiwala",
"Pumps": [
{
"id": "Shell.Bangalore.Madiwala.pump4"
},
{
"id": "Shell.Bangalore.Madiwala.pump5"
}
]
}
]
}
]
}
}
string result = await resp.Content.ReadAsStringAsync();
List<ListView11> _Resp = JsonConvert.DeserializeObject<List<ListView11>>(result);
//List<ListView11> _objList = new List<ListView11>((IEnumerable<ListView11>)_Resp);
IList usll = _Resp.Select(a => a.lttsdata).ToList();
// List<ListViewClass> _objList = new List<ListViewClass>((IEnumerable<ListViewClass>)_Resp);
//IList usll = _objList.OrderBy(a=> a.ReqID).ToList();
Lv.ItemsSource = usll;
I am looking for a JSON library which is able to do the following:
PC 1
JSONObject obj = new JSONObject();
obj.put("name", "mkyong.com");
obj.put("age", new Integer(100));
PC 2
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("name");
System.out.println(name);
long age = (Long) jsonObject.get("age");
System.out.println(age);
As you can see, there was no need to create a class in order to send the name and age value pairs. Now, this code is in Java. Is there a library in .NET which does this? I checked the documentation for JSON.NET, however it appears that it does not offer the use of a JSONobject where we can add value pairs.
You can use Json.Net
dynamic jsonObject = new JObject();
jsonObject.Name = "mkyong.com";
jsonObject.Age = 100;
var json = jsonObject.ToString();
output:
{
"Name": "mkyong.com",
"Age": 100
}
or without dynamic
JObject jsonObject = new JObject();
jsonObject["Name"] = "mkyong.com";
jsonObject["Age"] = 100;
var json = jsonObject.ToString();
You can even make use of anonymous classes
var json = JsonConvert.SerializeObject(new {Name="mkyong.com", Age=100 });