Need ideas how to parse the following JSON format - c#

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

Related

Jobject using .Add in a nested element

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

Trying to deserialize JSON into Dictionary<string, List<string>> in c#

I'm trying to deserialize JSON into a dictionary with strings as keys and lists of strings as values. The way I did it is this:
[
{
"key1": [
"value1.1",
"value1.2"
]
},
{
"key2": [
"value2.1",
"value2.2"
]
},
]
and to deserialize:
Dictionary<string, List<string>> dictionary;
string text = File.ReadAllText(#"Text.json");
dictionary = JsonConvert.DeserializeObject<Dictionary<string, List<string>>>(text);
I am receiving the errors:
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary2[System.String,System.Collections.Generic.List1[System.String]]' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '', line 1, position 1.'
Does anyone have have any insights for me?
Solution As Per Question:
Try this, Hopefully this will help you. https://dotnetfiddle.net/f3u1TC
string json = #"[{""key1"":[""value1.1"",""value1.2""]},{""key2"":[""value2.1"",""value2.2""]}]";
var dictionary = JsonConvert.DeserializeObject<Dictionary<string, List<string>>[]>(json);
Edit
Updated Solution:
If you don't need an array. Then you have to update your json. Remove array braces [] and add these ones {}
Json
{
{
"key1": [
"value1.1",
"value1.2"
]
},
{
"key2": [
"value2.1",
"value2.2"
]
},
}
C#
string json = #"{""key1"":[""value1.1"",""value1.2""],""key2"":[""value2.1"",""value2.2""]}";
var dictionary = JsonConvert.DeserializeObject<Dictionary<string, List<string>>>(json);
JSON syntax for dictionary is { "key1": "val1", "key2: "val2".....}
So if your JSON is structured as follows, your conversion will work as it is.
string json = #"{""key1"":[""value1.1"",""value1.2""],""key2"":[""value2.1"",""value2.2""]}";
var dictionary = JsonConvert.DeserializeObject<Dictionary<string, List<string>>>(json);

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!

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

How to parse JSON array (as a string) to Dictionary<string,string> in C#?

I have a string in the following format:
{ "Updated" : [ { "FIRST_NAME" : "Aaa", "LAST_NAME" : "Bbb" } ] }
How can I get a dictionary out of this so I can call dict["FIRST_NAME"]?
I've tried the following, but I think they don't work because my string is a JSON array? If that's the case, how do I change it to a regular JSON string? I don't think it needs to be an array with the simple type of data that is in it... The size of the array will never be more than 1 - i.e., there will be no repeating fields.
Dictionary<string, string> dict = serializer.Deserialize<Dictionary<string, string>>(jsonString); //didn't work
JArray jArray = JArray.Parse(jsonString); //didn't work
What you are having is a complex object, which can be parsed as a Dictionary of an Array of a Dictionary!
So you can parse it like:
var dic = serializer.Deserialize<Dictionary<string, Dictionary<string, string>[]>>(jsonString)["Updated"][0];
var firstName = dic["FIRST_NAME"];
var lastName = dic["LAST_NAME"];
It might be easier to just work with a dynamic variable. See Deserialize JSON into C# dynamic object? for more details.

Categories

Resources