Jobject using .Add in a nested element - c#

If I had a Json Object:
{
"data":{
"SomeArray":[
{
"name":"test1"
},
{
"name":"test2"
},
{
"name":"test3"
}
]
}
}
And this object is Parsed using Jobject.Parse(jsonString);
How would I add a field under data that holds the count of the items in the array to be forwarded tro another system. The count has already been calculated. I just need to add it in like this:
{
"data":{
"Count" : 3,
"SomeArray" : [
I have tried
myJObject["data"].Add("Count",count);
But .Add does not work here. The only option I see is AddAfterSelf()
Is there no way to just add a simple key value pair without having to create Jproperty first and add it using AddAfterSelf?
Or is the correct way: x["Data"].AddAfterSelf(new JProperty("Count", count));

The problem here is that myJObject["data"] returns an JToken which is base class for JObject.
If you're sure that "data" will be always an object, you can do following
var data = myJObject.GetValue("data") as JObject;
data.Add("Count",120);

You could do this by casting the JToken that you get from myJObject["data"] as a JObject. For example:
var data = (JObject)myJObject["data"];
data.Add("Count", 3);

Related

Need ideas how to parse the following JSON format

I have an API that returns JSON data in the following structure:
{
"85f78300-d993-4b7e-a8d0-8d39a4ba9d2a": {},
"4000fda7-18af-463f-b694-bbafe5d23a48": {
...
}
...
}
It should represents a list of objects referenced by a GUID. Typically a list of of Objects would look like this:
{
"objects": [
{...},
{...},
...
]
}
Currently I have no clue how to parse this result properly. Does anyone have a clue for me?
You could treat it as a Dictionary<Guid, object>. You can replace object with your data type.
string json = "{\"85f78300-d993-4b7e-a8d0-8d39a4ba9d2a\": {\"prop\": \"value\"}}";
var dict = System.Text.Json.JsonSerializer.Deserialize<Dictionary<Guid, object>>(json);

Deserialize JSON from Firebase

I have a JSON file from firebase that has a list of nodes with their own unique names, If possible I'd like to deserialize the contents all into a list just like a normal JSON array using Newtonsoft.Json like this:
using (StreamReader r = new StreamReader(filePath))
{
string json = r.ReadToEnd();
Console.WriteLine(json);
List<Card> items = JsonConvert.DeserializeObject<List<Card>>(json);
}
However Because of this JSON format from Firebase, each node has a unique name, is there any way to deserialize them like a normal JSON array without editing the format of the JSON using Newtonsoft.Json?
I can safely ignore the node name as I only need the contents of each objects and put them in a list.
{
"131F78DB" : {
"IDNumber" : "5526F",
"Name" : "NAME1"
},
"19505EAD" : {
"IDNumber" : "5132F",
"Name" : "TEMPORARYHR10103"
},
"19539B6D" : {
"IDNumber" : "10102",
"Name" : "TEMPORARYHR10102"
}
}
I will be working with large JSON files like this so if possible I'd like to avoid doing any manual string manipulation to remove the node names.
You can deserialize it as a Dictionary like this:
var items = JsonConvert.DeserializeObject<Dictionary<string, Card>>(json);
That way you can still iterate over it like a list, it matches the format of the json, and you still have all the information available (even if you don't need the key values).
If you really want to have it as a list you could add Select(x => x.Value).ToList() to create a List<Card>.

Is there a way to remove nodes from JSON.NET JObject of a certain type?

I've got a JSON object that's returned from an API and some of the nodes are arrays. Is there any way for me to pull those out of the object completely based on the "type" ?
for example:
{ "result" : {
"field1": "value1",
"field2" : [ "val2", "val3" ],
"field3" : "val4",
"field4" : "val5" }
}
I'd like to be able to remove "field2" because it's an array.
i'm not sure how to iterate through the object in a way that will give me the type of the object.
I'm using C# and JSON.NET 6.0.5
thanks!
After you parse the data do this:
jsonObject.Property("field2").Remove();
I think I've found the answer. Since you can use foreach with a JSON Object, all you have to do is check the type and choose to 'continue' or not
example:
foreach (var item in jobj)
{
if ( jobj[item.Key] is JArray )
{
continue;
}
// do what you would do with other types.
}
Thanks!

Getting the name / key of a JToken with JSON.net

I have some JSON that looks like this
[
{
"MobileSiteContent": {
"Culture": "en_au",
"Key": [
"NameOfKey1"
]
}
},
{
"PageContent": {
"Culture": "en_au",
"Page": [
"about-us/"
]
}
}
]
I parse this as a JArray:
var array = JArray.Parse(json);
Then, I loop over the array:
foreach (var content in array)
{
}
content is a JToken
How can I retrieve the "name" or "key" of each item?
For example, "MobileSiteContent" or "PageContent"
JToken is the base class for JObject, JArray, JProperty, JValue, etc. You can use the Children<T>() method to get a filtered list of a JToken's children that are of a certain type, for example JObject. Each JObject has a collection of JProperty objects, which can be accessed via the Properties() method. For each JProperty, you can get its Name. (Of course you can also get the Value if desired, which is another JToken.)
Putting it all together we have:
JArray array = JArray.Parse(json);
foreach (JObject content in array.Children<JObject>())
{
foreach (JProperty prop in content.Properties())
{
Console.WriteLine(prop.Name);
}
}
Output:
MobileSiteContent
PageContent
JObject obj = JObject.Parse(json);
var attributes = obj["parent"]["child"]...["your desired element"];
foreach (JProperty attributeProperty in attributes)
{
var attribute = attributes[attributeProperty.Name];
var my_data = attribute["your desired element"];
}
The default iterator for the JObject is as a dictionary iterating over key/value pairs.
JObject obj = JObject.Parse(response);
foreach (var pair in obj) {
Console.WriteLine (pair.Key);
}
Using Linq we can write something like:
JArray array = JArray.Parse(json);
foreach (JObject content in array.Children<JObject>())
{
List<string> keys = content.Properties().Select(p => p.Name).ToList();
}
If the JToken key name is unknown, and you only need the key's Value regardless of name, simply use the JToken.Values() method.
The below sample assumes the JToken value is a primitive type - first value found is extracted.
Solution can be extended to support Array values.
JToken fooToken = sourceData.
int someNum = fooToken .Values<int?>().First() ?? 0;
int someString = fooToken .Values<string>().First();
The simplest way is to look at the path of each item in the JSON object.
For Each token As JToken In json
Dim key= token.Path.Split(".").Last
Next

How can I order a not typed array?

JSON:
"media$thumbnail":[
{
"url":"https://i1.ytimg.com/vi/gL23XCv6rek/default.jpg",
"height":90,
"width":120,
"time":"00:08:11",
"yt$name":"default"
},
{
"url":"https://i1.ytimg.com/vi/gL23XCv6rek/mqdefault.jpg",
"height":180,
"width":320,
"yt$name":"mqdefault"
},
{
"url":"https://i1.ytimg.com/vi/gL23XCv6rek/hqdefault.jpg",
"height":360,
"width":480,
"yt$name":"hqdefault"
}
]
My code:
var thumbnailList = (JArray)item["media$group"]["media$thumbnail"];
and I'd like to extract the "url" with the max "width" value.
I should order this list with OrderByDescending(p => p.width), but of course I can't access to that typed value.
How can I do it? Is there a way on LINQ?
What you have getting is a JArray that you can enumerate to JTokens, and JToken has a method SelectToken that can get values nested inside of it.
Using Linq, you'd end up with something similar to;
OrderByDescending(t => Convert.ToInt32(t.SelectToken("width")))

Categories

Resources