How do i deserialize this dictionary<string,string[]> - c#

I have the following json :
[
{
"Key": "tradepack",
"Value": [
"Select Tradepack"
]
},
{
"Key": "route",
"Value": [
"Select Route"
]
},
{
"Key": "recall",
"Value": [
"Select Recall Location"
]
},
{
"Key": "stones",
"Value": [
"True"
]
},
{
"Key": "quickstep",
"Value": [
"True"
]
},
{
"Key": "dreamingdonkey",
"Value": [
"True"
]
},
{
"Key": "meleeskills",
"Value": []
},
{
"Key": "rangedskills",
"Value": []
},
{
"Key": "buffedskills",
"Value": []
}
]
Im currently using this
String data = System.IO.File.ReadAllText(Application.StartupPath + "\\folder\\Data\\Config\\config.txt");
return JsonConvert.DeserializeObject<Dictionary<string, object[]>>(data);
but i get the following error
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[System.String,System.Object[]]' 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.
Anyone care to explain as how i would solve this im a newb in c# especially serialization

Your json is an array/list. So you need to deserialize to something like this List<Dictionary<string, object>>
var data = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(json);
OR
var dict = JArray.Parse(json)
.Select(x => x.ToObject<KeyValuePair<string, string[]>>())
.ToDictionary(x => x.Key, x => x.Value);

Your data looks more like a KeyValuePair<string, string[]>[]. You can try deserializing to that, then creating a dictionary based on the result.
var kvps = JsonConvert.DeserializeObject<KeyValuePair<String, String[]>[]>(data);
return kvps.ToDictionary((keyItem) => keyItem.Key, (valueItem) => valueItem.Value);

Related

Deserializing random json file in c#

i am trying to take in a json file and iterate over some of the values.
The file is 73000 lines long, and i only need a few values.
Here is an example of the json file:
{
"value" : "key"
"value" : "key"
"Owner": {
"UserId": xxx,
"Username": "xxx",
},
"Items": [
{
"value": "key",
"value": "key",
"Comment": "",
"value": {
"value": {
"value": "key",
"value": "key",
"value": "key",
}
},
"CustomFields": [
{
"Name": "something",
"Content": "true"
}
]
}
]
}
How do i load this in without defining the object? i need 5 values per item, from different nesting levels, though i dont want to define the class as the file is more than 70.000 lines.
I tried doing it like this:
var values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
But that way i will get an error when i try to itterate over items, as items value will now be a string!
foreach (Dictionary<string, string> result in values["items"])
Is there a way to load the file, defining the class based on the json schema?
I need values from different levels in the file, some at root level some nested.

Transform a JSON object to a JSON array, taking the first level of properties

I've this JSON object
{
"08f4f705-6e14-4781-8241-d04bf2dc6ada": {
"description": "xxxxxxxx",
"note": "yyyyyyyy"
},
"05f4f995-6e14-4567-8241-d04bf2d456ee": {
"description": "aaaaaa",
"note": "bbb"
},
"0675f995-6e14-4567-8241-d4567f2d456z": {
"description": "fffff",
"note": "gggg"
}
}
I need to convert into a JSON array like this:
(the elements should be the content of the first level properties)
[
{
"description": "xxxxxxxx",
"note": "yyyyyyyy"
},
{
"description": "aaaaaa",
"note": "bbb"
},
{
"description": "fffff",
"note": "gggg"
}
]
I can't manipulate the object and I didn't find an appropriate resource to follow. How can I do it?
You can achieve this by deserializing your json string into Dictionary<string, object>:
var obj = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
After that you extract the values and serialize them back to json:
var newJson = JsonConvert.SerializeObject(obj.Values);

access value in JSONArray C# UWP

I want to extract the first value in a JSONArray as String. Somehow I have the wrong approach, I get an exception.
How can I improve this?
I think I reach the array fine via myJasonObject["entities"].toArray(), but when I try to do something like getString()["entity"] afterwards, it's marked as error by VS.
I want to be able to store "dax" (the value of "entity"):
Response{
"query": "what about dax",
"topScoringIntent": {
"intent": "StockPrice2",
"score": 0.3969668
},
"intents": [
{
"intent": "StockPrice2",
"score": 0.3969668
},
{
"intent": "None",
"score": 0.372112036
},
],
"entities": [
{
"entity": "dax",
"type": "StockSymbol"
}
]
}
You can get "dax" using following:
JObject obj = JObject.Parse(json);
JArray entities = obj.GetValue("entities") as JArray;
var firstEntity = entities.FirstOrDefault() as JObject;
var entityPropertyValue = entity.GetValue("entity");
var daxString = entityPropertyValue.ToString();

Accesing child value in JSON

How can i acces the first item id?
using (var http = new HttpClient())
{
var res = JArray.Parse(await http.GetStringAsync("http://api.champion.gg/champion/Gragas?api_key=????").ConfigureAwait(false));
^^^^^^ // Also tried with JObject instead of JArray, both don't work
var champion = (Uri.EscapeUriString(res[0]["items"][0]["mostGames"][0]["items"][0]["id"].ToString()));
Console.WriteLine(champion); // ^ [0] here because the JSON starts with an [
}
Example JSON result (made it smaller because the original JSON is over 21500 characters, made sure its valid with https://jsonlint.com, here is the original JSON response: https://hastebin.com/sacikozano.json)
[{
"key": "Gragas",
"role": "Jungle",
"overallPosition": {
"change": 1,
"position": 13
},
"items": {
"mostGames": {
"items": [{
"id": 1402,
"name": "Enchantment: Runic Echoes"
},
{
"id": 3158,
"name": "Ionian Boots of Lucidity"
},
{
"id": 3025,
"name": "Iceborn Gauntlet"
},
{
"id": 3065,
"name": "Spirit Visage"
},
{
"id": 3742,
"name": "Dead Man's Plate"
},
{
"id": 3026,
"name": "Guardian Angel"
}
],
"winPercent": 50.45,
"games": 300
}
}
}]
With JArray i get the following error: Accessed JObject values with invalid key value: 0. Object property name expected.
With JObject i get the following error: Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1.
Thanks in advance, i hope i explained it well
It should be:
var champion = (Uri.EscapeUriString(res[0]["items"]["mostGames"]["items"][0]["id"].ToString()));
The outermost "items" property has a single object as its value, not an array, so [0] is not needed in ["items"][0]. Similarly "mostGames" has a single object value so the [0] is not needed in ["mostGames"][0].
Sample fiddle.
Note that if "items" is sometimes an array of objects, but sometimes is a single object instead of an array of one object, you can introduce the following extension method:
public static class JsonExtensions
{
public static IEnumerable<JToken> AsArray(this JToken item)
{
if (item is JArray)
return (JArray)item;
return new[] { item };
}
}
And do:
var champion = (Uri.EscapeUriString(res[0]["items"].AsArray().First()["mostGames"]["items"][0]["id"].ToString()));

How to add a root node to a JSON in C# using Json.NET?

I am working on Visual Studio C# project and I need to convert a JSON to XML.
I receive the JSON in string format.
The problem is, I need to have a root node in the JSON structure if the JSON doesn't have one, so that I can convert to XML with desired format.
Supose I have this JSON:
{
"id": 1,
"name": {
"first": "Yong",
"last": "Mook Kim"
},
"contact": [{
"type": "phone/home",
"ref": "111-111-1234"
}, {
"type": "phone/work",
"ref": "222-222-2222"
}]
}
And I want to add root node to that JSON just like that:
{
"user": {
"id": 1,
"name": {
"first": "Yong",
"last": "Mook Kim"
},
"contact": [{
"type": "phone/home",
"ref": "111-111-1234"
}, {
"type": "phone/work",
"ref": "222-222-2222"
}]
}
}
How can I do it with C# and JSON.NET?
I suppose you have user object. Just use anonymous class to add extra root node:
var obj = new { user = user };
string json = JsonConvert.SerializeObject(obj);
The resulting JSON will look like that:
{
"user": {.../your user object/...}
}

Categories

Resources