Accessing JSON Body with C# - c#

I need to access the body of a JSON Code with C#. Accessing the header works but it does not work with the body and I could not find anything in the web.
I have this JSON Code
`{
"Example": {
"Header": [
[
"Header1",
"Header2",
"Header3",
"Header4"
]
],
"Body": [
{
"Header1": "BlaBla",
"Header2": 0,
"Header3": 20,
"Header4": 32
},
{
"Header1": "BlaBlaBla",
"Header2": 22,
"Header3": 35,
"Header4": 25
},
......`
However I can acess the headers with following code:
JArray headers = locationsObject["Header"] as JArray;
JArray header = headers.Last as JArray; //Last Header
If I do the same with the body it is null:
JArray bodys = locationsObject["Body"] as JArray; //all bodys -> it works here
JArray body = bodys.First as JArray; //First body -> this one is null!!!
I need the integers in the body. I am using Newtonsoft for that. Can someone help me please? Thank you very much!

your first body is not a JArray that could be the source of the problem, it is rather a JObject, you can try the following code, it should work fine
var bodys = locationsObject["Body"] as JArray;
var body = bodys[0];
you can use also linq-to-json for more fine-tuned operations.

I recommend you to look at serializing/deserializing json in c#.
How to serialize and deserialize (marshal and unmarshal) JSON in .NET
If you do not have a class representation of the json json to c#
Your main line of code will be something like this:
exObj = JsonSerializer.Deserialize<ExampleObject>(jsonString);
And it will be:
string header1 = exObj.Body.Header1;

One way of doing this is by using the 'dynamic' variable type of C# which was specifically designed for functional programming languages. It is not type safe and not strong typed but you can access all the values in the result.
I would however strongly recommend you create classes that mimic the json you are trying to deserialize for it will give you strong typing and intellisense.
Here's an example how you can use dynamic. You need to install the NewtonSoft.Json Nuget package for this to function correctly.
using Newtonsoft.Json;
using System;
namespace JsonDeserialized
{
class Program
{
static void Main(string[] args)
{
string json = #"{
'Example':
{ 'Header':
[
[
'Header1',
'Header2',
'Header3',
'Header4'
]
],
'Body':
[
{
'Header1': 'BlaBla',
'Header2': 0,
'Header3': 20,
'Header4': 32
},
{
'Header1': 'BlaBlaBla',
'Header2': 22,
'Header3': 35,
'Header4': 25
}
]
}
}";
var result = JsonConvert.DeserializeObject<dynamic>(json);
Console.WriteLine(result.Example);
foreach (var header in result.Example.Header[0])
{
Console.WriteLine(header);
}
Console.WriteLine(result.Example.Header[0][0]);
}
}
}
This program will print the following result.
{
"Header": [
[
"Header1",
"Header2",
"Header3",
"Header4"
]
],
"Body": [
{
"Header1": "BlaBla",
"Header2": 0,
"Header3": 20,
"Header4": 32
},
{
"Header1": "BlaBlaBla",
"Header2": 22,
"Header3": 35,
"Header4": 25
}
]
}
Header1
Header2
Header3
Header4
Header1

Related

How to Format the nested string json property serialized json in C#

I am facing problem to serialized or format nested string JSON.
Here is the input: Data can have dynamic values
{
"Id": 33,
"Data": "{\n \"$Datatype\": \"Val1, Val2\"\n }",
"Name": "Test"
}
I want the output without any special characters like \n, , \ etc like:
{
"Id": 33,
"Data": {
"$Datatype": "Val1, Val2"
},
"Name": "Test"
}
Data property was serialized twice. To fix it try this code
var jsonParsed = JObject.Parse(json);
jsonParsed["Data"] = JObject.Parse((string) jsonParsed["Data"]);
json = jsonParsed.ToString();

How to update JArray values with C# and Json.NET

I'm getting an array of items from Web API (lines before this are omitted):
var cars = JArray.Parse(response.Content.ReadAsStringAsync().Result)
Inside the cars JArray it looks like this:
"cars": [{
"id": 1,
"make": "Audi",
"color": "red"
}, {
"id": 2,
"make": "Mercedes",
"color": "red"
}, {
"id": 3,
"make": "Ford",
"color": "yellow"
}]
I would like to update the color of Ford to red if Audi is also red.
How can I do that with C# and Json.NET?
The JSON you provided is not valid for me to parse, so ive made an assumption to demonstrate. which wraps your sample in a root JSON object.
You can query the JOBject using keys. i.e to access cars propery in the JSON you can use o["cars"]. With this approach you can see i use a bit of Linq to figure out if Audi is red, and if so, you can perform direct modifications to the o object and set values accordingly.
This is the most basic approach, without any further code.
void Main()
{
var json = #"
{
""cars"": [
{ ""id"": 1, ""make"": ""Audi"", ""color"": ""red"" },
{ ""id"": 2, ""make"": ""Mercedes"", ""color"": ""red"" },
{ ""id"": 3, ""make"": ""Ford"", ""color"": ""yellow"" }
]
}";
var jObject = Newtonsoft.Json.Linq.JObject.Parse(json);
var jArray = jObject["cars"] as JArray;
Console.WriteLine("Before: " + JsonConvert.SerializeObject(jObject));
var audiIsRed = jArray.Any(car => car.Value<string>("make").Equals("Audi") && car.Value<string>("color").Equals("red"));
if (audiIsRed)
{
jArray.First(c => c.Value<string>("make").Equals("Ford"))["color"] = "red";
}
Console.WriteLine("After: " + JsonConvert.SerializeObject(jObject));
}
An alternative could be making a POCO to deserialize the results, which would contain, for example a List<Car> and then you could do all modifications with C# and no JSON.NET then serialize that result back to JSON.

Looping through JObject nested array

I can not figure out exactly how to did through this JObject in order to retrieve the id property under runs.
I have this following code which will successfully give me the id property that is under entries, but how can I nest this again to go into the runs sections and get those ID's?
JSON:
{
"id": 168,
"name": "section 1",
"entries": [
{
"id": "908-9876-908",
"suite_id": 15,
"name": "List 1",
"runs": [
{
"id": 169,
"suite_id": 15
}
]
},
{
"id": "998-4344-439",
"suite_id": 16,
"name": "List 2",
"runs": [
{
"id": 170,
"suite_id": 16
}
]
}
]
}
C# Code:
JObject obj = JsonConvert.DeserializeObject<JObject>(response);
foreach (JObject id in obj["entries"])
{
string returnable = (string)id["id"];
Console.WriteLine(returnable);
}
I have tried looking at ["entries"]["runs"] but that also was not working.
The print out of this is:
908-9876-908
998-4344-439
What I would like is
169
170
You can achieve it using the following code
var jsonObject = JObject.Parse(json);
foreach (var entry in jsonObject["entries"])
{
foreach (var run in entry["runs"])
{
string returnable = (string)run["id"];
Console.WriteLine(returnable);
}
}
You would like to see
169
170
They are an id values from runs array, therefore you should enumerate them in the inner loop. You've also missed a comma after "name": "section 1"
You can use SelectTokens() to query for nested data inside a JToken hierarchy. It provides support for JSONPath queries including wildcards [*] for arrays:
var ids = obj.SelectTokens("entries[*].runs[*].id").Select(i => (long)i).ToList();
See: Querying JSON with complex JSON Path.
Demo fiddle here.

C# get value from deserialized json object

I'm currently Deserializing a json string using the Newtonsoft.Json nuget packet using the following code:
var data = (JObject)JsonConvert.DeserializeObject(json);
Now I'm receiving an object in the following format:
{{ "meta": { "rap": 2098, "count": 5 }, "data": [ { "name": "Gold Tetramino of Mastery", "rap": 735, "uaid": "16601901", "link": "https://www.roblox.com/Gold-Tetramino-of-Mastery-item?id=5786047", "img": "https://t4.rbxcdn.com/081337d7ea86e6a406512aaa83bbcdeb", "serial": "---", "count": 1 }, { "name": "Silver Tetramino of Accomplishment", "rap": 385, "uaid": "16601900", "link": "https://www.roblox.com/Silver-Tetramino-of-Accomplishment-item?id=5786026", "img": "https://t1.rbxcdn.com/60da69cd76f8dad979326f63f4a5b657", "serial": "---", "count": 1 }, { "name": "Subzero Ski Specs", "rap": 370, "uaid": "155175547", "link": "https://www.roblox.com/Subzero-Ski-Specs-item?id=19644587", "img": "https://t4.rbxcdn.com/8ead2b0418ef418c7650d34103d39b6d", "serial": "---", "count": 1 }, { "name": "Rusty Tetramino of Competence", "rap": 319, "uaid": "16601899", "link": "https://www.roblox.com/Rusty-Tetramino-of-Competence-item?id=5785985", "img": "https://t2.rbxcdn.com/968ad11ee2f4ee0861ae511c419148c8", "serial": "---", "count": 1 }, { "name": "Bluesteel Egg of Genius", "rap": 289, "uaid": "16601902", "link": "https://www.roblox.com/Bluesteel-Egg-of-Genius-item?id=1533893", "img": "https://t7.rbxcdn.com/48bf59fe531dd1ff155e455367e52e73", "serial": "---", "count": 1 } ]}}
Now I'm trying to get the following value from it:
"rap": 2098,
I just need 2098 and I've been trying the following code:
string rap = data["rap"].Value<string>();
But sadly this wouldn't work. Does anyone have a idea how to get the value?
Try:
var result = data["meta"]["rap"].Value<int>();
or
var result = data.SelectToken("meta.rap").ToString();
or if you don't want to want to pass the whole path in, you could just search for the property like this:
var result = data.Descendants()
.OfType<JProperty>()
.FirstOrDefault(x => x.Name == "rap")
?.Value;
Instead of declaring as type var and letting the compiler sort it, declare as a dynamic and using the Parse method.
dynamic data = JArray.Parse(json);
Then try
data.meta.rap
To get the internal rap object.
I edited from using the deserializeobject method as i incorrectly thought that had the dynamic return type. See here on json.net documentation for more details: http://www.newtonsoft.com/json/help/html/QueryJsonDynamic.htm
I just came to add Yet another way to get 2098:
After having got your object in the way you actually did:
var data = (JObject)JsonConvert.DeserializeObject(json);
The first you have to note is that the value you want to get is itself a value of the property "meta":
so, first you have to extract the contents of "meta" by simply calling
data["meta"]
and just then you are able to ask for the Value<string> of "rap":
String rap = data["meta"].Value<string>("rap");
which acctually gives you the value you were looking for:
Console.WriteLine(rap); // 2098
var jobject = (JObject)JsonConvert.DeserializeObject(json);
var jvalue = (JValue)jobject["meta"]["rap"];
Console.WriteLine(jvalue.Value); // 2098
The value is actually an int type. Try:
int rap = data["rap"].Value<int>();
string rap = JsonConvert.DeserializeObject<dynamic>(json).meta.rap;
Console.WriteLine(rap); // 2098
If you're not into dynamic (or aren't using .NET 4+), I like how this other answer relies solely on Json.NET's API.
Try to use as following
var test = JsonConvert.DeserializeObject<dynamic>(param);
var testDTO = new TPRDTO();
testDTO.TPR_ID = test.TPR_ID.Value;
Note: For using of JsonConvert class you have to install Newton-Soft from your package-manager
the problem is that you are casting the deserialized json into a JObject. if you want to have the JObject then simple do this:
JObject.Parse(json);
then you have the JObject and you can access a specific path (for extracting value see this )
you have also another option which is to deserialize your json into a class that you have in your code like this:
var instanceOFTheClass = JsonConvert.DeserializeObject<YourClassName>(json);
with the above code you can access any property and values you want.
Use the enumerator to get at the value:
var data = (JObject)JsonConvert.DeserializeObject(json);
var enumerator = data.GetEnumerator();
enumerator.MoveNext();
var dataValue = enumerator.Current.Value.ToString();
Just use dynamic representation of object:
dynamic obj = JsonConvert.DeserializeObject(json)
var value = obj.meta.rap;
JObject easily convertable to dynamic type itself. You can either get string or int from this value:
var ivalue = (int)obj.meta.rap;
var svalue = (string)obj.meta.rap;

JSON.NET reader problem

i got some problem when i generate .json file from spring .json ,and i got this format
{ "models": [
{
"id":1,
"modelName":"dfdsf",
"created":{
"userFullname":"demo",
"time":"150301",
"date":"20110208",
"userId":"123"
},
"remark":"dsfdf",
"updated":"~unique-id~1"
},
{
"id":2,
"modelName":"test",
"created":{
"userFullname":"test",
"time":"150301",
"date":"20110210",
"userId":"124"
},
"remark":"test",
"updated":{
"userFullname":"test",
"time":"150301",
"date":"20110209",
"userId":"test"
}
}
]}
first time i used JObject Parse for convert
JObject job = JObject.Parse(fullJson);
and the other hand i used jtoken to focus "models"
JToken jDetail = job["models"];
but the problem is {[{ xxx }]} it look like jarray i don't have any idea to convert it
i ever use JArray, JsonTextReader but it doesn't work.
could suggestion some? because if i pass this ll i set some value to object.
thank you for every idea.
string fullJson = File.ReadAllText("TextFile1.txt"); // for brevity
var job = JObject.Parse(fullJson);
var models = job.Value<JArray>("models");
Console.WriteLine(models[0]);
result:
{
"id": 1,
"modelName": "dfdsf",
"created": {
"userFullname": "demo",
"time": "150301",
"date": "20110208",
"userId": "123"
},
"remark": "dsfdf",
"updated": "~unique-id~1"
}

Categories