How to deserialize JSON to Dictionary using JSON.NET? - c#

I am querying data from http://www.imdbapi.com and would like to parse the result using Json.net library. Could someone please tell me how I can use this library to convert the query response into a Map<string, string>.
With this code I'm able to get all keys, but how can query the values then?
JObject obj = JObject.Parse(response);
IList<string> props = obj.Properties().Select(p => p.Name).ToList();

Try JSON.NET
Just use this:
Dictionary<string, string> movieValues =
JsonConvert.DeserializeObject<Dictionary<string, string>>(responseFromImdbApi);
Just get the values like this:
movieValues["title"]
movieValues["released"]
movieValues["genre"]

Why would you use an external library when it is already available ?
JavaScriptSerializer works great.

Related

C# Serializing an objects into JSON but retain the name

So I'm trying to serialize a Dictionary:
Dictionary<string, List<MyClass>>
My class contains a property called MyPropery
However the string comes out as "{"List1":[{"MyProperty":[]}]}"
How would I be able to make it convert to {"List1":["MyClass":{"MyProperty":[]}]}
To achieve what you want, you would need something like:
var obj = new Dictionary<string, List<Dictionary<string, MyClass>>>();
As kalimag pointed out, ["attr": "value"] isn't a valid JSON. The serialization of the object obj, illustrated above, could yield something like:
{"List1": [{"MyClass": {"MyProperty": []}}]}
Which is a valid JSON.

C# Json deserialize - property as variable

I have problem. From json: https://api.csgofast.com/price/all I would like to get property name as variable. Can I do it with Newtonsoft Json library? Thanks in advance for help.
You can deserialize this JSON into a Dictionary<string, decimal> like this:
var prices = JsonConvert.DeserializeObject<Dictionary<string, decimal>>(json);

Working with a string in JSON format

I have a long string in JSON format. This is what it looks like:
{"ShowMapUrl":true,"GameDiffusionType":5,"InputYellowCards":false,"DisplayYellowCards":false,"InputYellowCards2":false}
Note that the string is much longer. I've been trying to convert that string into a dictionary by using json.NET without success. Any tips?
Use JsonConvert.DeserializeObject<Dictionary<string, object>>():
var json = #"{""ShowMapUrl"":true,""GameDiffusionType"":5,""InputYellowCards"":false,""DisplayYellowCards"":false,""InputYellowCards2"":false}";
var dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);

c# - deserialization of specific JSON

I have JSON text with structure like this:
{
"324523":{"a":1345, "b":2344},
"134565":{"a":1642, "b":2322},
"123426":{"a":1556, "b":2674},
...
}
Is it possible to make .NET classes to deserialize such JSON? It looks like a Dictionary, but DataContractJsonSerializer doesn't deserialize this.
Try JSON.Net, which you can obtain from NuGet, or from the JSON.Net website.
Deserializing:
var jsonValues = JsonConvert.DeserializeObject(someJsonString);
var pocoValue = JsonConvert.DeserializeObject<YourClass>(someJsonString);
// or as a dictionary:
var dictionary = JsonConvert.DeserializeObject<Dictionary<MyClass>>(someJsonString);

How can I get a list of keys from Json.NET?

I'm using C# and Json.NET. If I have a JObject, I want a list of the keys within the object, similar to how object.Keys() returns the keys within the object. This seems like it'd be obvious, but I'm having a rough time finding a way to do this.
Edit:
I'm traversing through the object, and I want to spit out all the keys in the object as I go through. I realize that this example will result in seeing the same key multiple times, and that's OK for my needs.
public void SomeMethod(JObject parent) {
foreach (JObject child in parent.Children()) {
if (child.HasValues) {
//
// Code to get the keys here
//
SomeMethod(child);
}
}
}
IList<string> keys = parent.Properties().Select(p => p.Name).ToList();
Documentation: JObject.Properties
From Converting a JSON.NET JObject's Properties/Tokens into Dictionary Keys
You can simply convert the JObject into a Dictionary object and access the method Keys() from the Dictionary object.
Like this:
using Newtonsoft.Json.Linq;
//jsonString is your JSON-formatted string
JObject jsonObj = JObject.Parse(jsonString);
Dictionary<string, string> dictObj = jsonObj.ToObject<Dictionary<string, string>>();
You can now access those keys via the dictObj.Keys() method. You can see if a key exists by performing dictObj.ContainsKey(keyName) also.
Obviously, you can format the Dictionary however you want (could be Dictionary<string, object>, etc.).

Categories