insert data into existing JSON Array in C# - 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");

Related

Add property to each object in JSON 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);

Add a Root Key for an Orphan JSON using C#

I need to add a Key for the Orphan JSON object
JSON String:
string jsonString = "{\"FirstName\":\"Emma\",\"LastName\":\"Watson\"}";
Expected JSON String:
string jsonString = "{\"PersonName\":{\"FirstName\":\"Emma\",\"LastName\":\"Watson\"}}";
I need to add a Key for the above said actual JSON string as like expected JSON using C#.
I tried the following code:
string rootKey = "PersonName";
string jsonString = "{\"FirstName\":\"Emma\",\"LastName\":\"Watson\"}";
var jObj = JObject.Parse(jsonString);
// Need to add a ROOT Key for this jObj...
Simillar to the existing question How to add a key to a JSON array value?
You're not adding a property to the object, you're putting the object in another object. Just think of it as a dictionary. Create a "dictionary" and add your object to it. Then you could get the json string back from that object.
var jsonString = "{\"FirstName\":\"Emma\",\"LastName\":\"Watson\"}";
var jsonObj = JObject.Parse(jsonString);
var newObj = new JObject
{
["PersonName"] = jsonObj,
};
var newJsonString = newObj.ToString();

How can i access any key inside of json string via C#?

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

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

Take the information from json

I'm trying to parse "VID" from this json data
{"response":[2,{"vid":165971367},{"vid":165971350}]}.
But it don't want to parse it. I think there is problem with "2" in json data. How to eliminate this figure?
Here is my code:
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("some json data");
string googleSearchText = await response.Content.ReadAsStringAsync();
JObject googleSearch = JObject.Parse(googleSearchText);
IList<JToken> results = googleSearch["response"].Children().ToList();
IList<SearchResult> searchResults = new List<SearchResult>();
If you were usng Json.Net and loaded that json into a JObject then you have a property called "response" so:
myJson["response"]
which is a JArray with 3 elements, so skip the first element.
.Skip(1)
Then you have IEnumerable and want property "vid", so something like:
var myVids = (from vids in myJObject["response"].Skip(1)
where vids["vid"] != null
select vids["vid"])
/* JSON
{"response":
[2,
{"vid":165971367},
{"vid":165971350}
]
}
*/
Of course, this is just the concept and you would need to adjust for real life.
You can skip the first item by using Skip method:
IList<JToken> results = googleSearch["response"].Skip(1).ToList();

Categories