Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize JSon string using JSON.NET

Tags:

json

c#

json.net

I am trying to deserialize the following JSon string so that I can capture the values in a b c d ...

{
   "2012-11-26 20:34:12": {
    "a": 65,
    "b": -1,
    "c": "2012-11-26 20:34:12",
    "d": -1,
    "e": 0,
    "f": -112.3211156215747,
    "g": 33.57955864376957
  }
}

JSonlint says that is valid JSon data, but what kind of class would I create in C# to use the JSON.NET JsonConverter to deserialize it ?

I am going to get more data like this and the key will vary ( currently shown as "2012-11-26 20:34:12" ) which is the part that is confusing me.

Any sample code to get me started would be greatly appreciated

like image 978
timmortonni Avatar asked Nov 27 '12 16:11

timmortonni


People also ask

How do I deserialize a string in C#?

Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method. For the generic overloads, you pass the type of the class you created as the generic type parameter. For the non-generic overloads, you pass the type of the class you created as a method parameter.

How do I deserialize JSON?

We can implement JSON Serialization/Deserialization in the following three ways: Using JavaScriptSerializer class. Using DataContractJsonSerializer class. Using JSON.NET library.

How do you deserialize a JSON string in Python?

To deserialize the string to a class object, you need to write a custom method to construct the object. You can add a static method to ImageLabelCollection inside of which you construct Label objects from the loaded JSON dictionary and then assign them as a list to the class variable bbox.

What is Jsonconvert SerializeObject C#?

SerializeObject Method (Object, Type, JsonSerializerSettings) Serializes the specified object to a JSON string using a type, formatting and JsonSerializerSettings. Namespace: Newtonsoft.Json.


1 Answers

You don't need any class

var obj = (JObject)JsonConvert.DeserializeObject(json);

var dict = obj.First.First.Children().Cast<JProperty>()
            .ToDictionary(p => p.Name, p =>p.Value);

var dt =  (string)dict["c"];
var d = (double)dict["g"];
like image 102
L.B Avatar answered Oct 16 '22 23:10

L.B