Add a Root Key for an Orphan JSON using C# - 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();

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

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

Extract first element from JSON

How can I take just the first element from a Json?
//take result back
void HandleIncomingMessage(object sender, PEventArgs e)
{
RetMessage += e.Result;
//here can not deserialize correct
var deserialized_message = JsonConvert.DeserializeObject<Message>(RetMessage);
}
Here I am doing the deserialize but because it`s taking the entire object can not parse it correct.
I need just JSON.[0]
Edit: Raw Json :
[{"unique_id":55,"action_name":"INSERT","start_date":"2018-06-11T16:00:00","end_date":"2018-06-11T17:00:00"},"1sddsd","my_channel"]
Deserialize to List<dynamic>, then read the properties of its first element.
//using Newtonsoft.Json;
var input = #"[{""unique_id"":55,""action_name"":""INSERT"",""start_date"":""2018-06-11T16:00:00"",""end_date"":""2018-06-11T17:00:00""},""1sddsd"",""my_channel""]";
var output = JsonConvert.DeserializeObject<List<dynamic>>(input);
Console.WriteLine(output[0].unique_id);
Output:
55
DotNetFiddle
How about getting json string and using JSON.net
//first create object from json
JObject jObject = JObject.Parse(jsonString);
//read unique value
string jUniqueId = jObject["unique_id"];
//or
string firstObject = jObject[0];
the solution is for static,
JObject obj= JObject.Parse(here pass the JSON);
string id= JSON[0]["unique_id"],
string name= JSON[0]["action_name"],
string sdate= JSON[0]["start_date"],
string edate= JSON[0]["end_date"]
dynamic means pass i instead of 0.

Newtonsoft.Json, How to code generic selection

Further on with Newtonsoft.Json, Path returned multiple tokens,
For this code:
JObject o = JObject.Parse(jsStr);
IEnumerable<JToken> selEnum = o.SelectTokens(theFilter);
where the jsStr is the content of https://api.github.com/search/repositories?q=Newtonsoft.Json&sort=stars&order=desc, and theFilter can be any valid JPATH query string (e.g., ".items" or ".items[*].owner").
How to return the selected as a valid json string?
It sounds like you just need Json.SerializeObject:
var o = JObject.Parse(jsStr);
var selEnum = o.SelectTokens(theFilter);
var newJson = JsonConvert.SerializeObject(selEnum);
This will give you JSON representing an array of all of the owner values from the original JSON.

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

Categories