Add property to each object in JSON C# - c#

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);

Related

insert data into existing JSON Array in C#

I need to add some more data into existing JSON
eg:
{
"OrderId":"abc",
"products":["a","b","c","etc"]
}
how to add more into products
The approach would be similar to used in answer to your previous question, but you will need to convert element to JArray:
var x = #"{
'OrderId':'abc',
'products':['a','b','c','etc']
}";
var jObj = JObject.Parse(x);
((JArray)jObj["products"]).Add("new");
Try this:
var jObject = JObject.Parse(json);
var jArray = jObject["products"] as JArray;
jArray?.Add("new_product");

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

Removing an element from a JSON response

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);

How to list a newtonsoft Jtoken or JObjects children in a listBox

I have a json file that i read to string and then convert to a jobject. I get a JToken from this object by selecting one of its children.
I want to list this JTokens children in a Listbox. I think, to do this i need to convert th eJTOken to a ListItem - how can i do this? If there is a better alternative way then would be interested to hear it!
string filePath = #"C:\output.json";
JObject json = JObject.Parse(System.IO.File.ReadAllText(filePath));
JToken jsonFiles = json["Files"];
jsonFilesListItem = ....
JsonListBox.Items.Add(jsonFilesListItem);
Assuming that json["Files"] contains a simple array of strings, all you have to do is use a foreach loop, as shown in the example below:
string jsonString = #"
{
""Files"": [
""foo.xml"",
""bar.txt"",
""baz.jpg"",
""quux.wav""
]
}";
JObject json = JObject.Parse(jsonString);
JToken jsonFiles = json["Files"];
foreach (string fileName in jsonFiles)
{
JsonListBox.Items.Add(fileName);
}

How to read property names in array from json string?

Here is the list of data I receive, property names are can be different;
{"data":"[
{
"id":"1",
"name":"aa",
"email":"aa#aa.com",
"address":"11"
},
{
"id":"2",
"name":"bb",
"email":"bb#bb.com",
"address":"22"
}
]"}
Here is my c# code
Which I get an error on the 3rd line. Unable to read json data. Check the url you typed.Invalid cast from 'System.String' to 'Newtonsoft.Json.Linq.JObject'.
var jsonStr = wc.DownloadString(url);
JToken outer = JToken.Parse(jsonStr);
JObject inner = outer["data"].Value<JObject>();
List<string> keys = inner.Properties().Select(p => p.Name).ToList();
How can my output be like this;
id
name
emal
address
It would be great if I also consider n level array such as address > street and address > postcode
Many thanks.
var jObj = JObject.Parse(json);
var props = jObj["data"][0].Select(x => ((JProperty)x).Name).ToList();
BTW: your json is not correct, it should be something like this
{data:[
{ "id":"1",
"name":"aa",
"email":"aa#aa.com",
"address":"11"
},
{"id":"2",
"name":"bb",
"email":"bb#bb.com",
"address":"22"
}
]}
See the " after data: in your question

Categories