dakt
dakt

Reputation: 650

Painless JSON deserialization in C# using JSON.NET

What is the most painless way to deserialize this JSON in C# using JSON.NET?

{
"serNo":{
            "A4":{
                    "vol":[["0","100","0,1"],["0","n","0"]],
                    "fix":"900"
                    },
            "A3":{
                    "vol":[["0","200","0,5"],["0","n","0"]],
                    "fix":"700"
                    }
        }
}

To create a separate class or as collection?

EDIT: There will be multiple "serNo" properties.

Upvotes: 1

Views: 1078

Answers (5)

dakt
dakt

Reputation: 650

OK, I solved the problem with JSON.NET by creating this class:

class Counter
{
   public double[][] vol { get; set; }

   public double fix { get; set; }
}

and

deserialized JSON with this expression:

Dictionary<string, Dictionary<string, Counter>> counters = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, Counter>>>(arg.Args[7]);

Where arg.Args[7] is JSON.

Upvotes: 1

ntziolis
ntziolis

Reputation: 10231

You can use the build in lightweight JavaScriptSerializer. No attributes are required on the classes you want to serialize/deserialize.

It can also handle anonymous types.

Serialization:

var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var objectAsJsonString = serializer.Serialize(objectToSerialize);

Deserialization:

var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
SomeClass deserializedObject = serializer.Deserialize<SomeClass>(objectToDeserialize);

Here is the link to an earlier related question/answer: Error converting JSON to .Net object in asp.net

Upvotes: 1

Roy Dictus
Roy Dictus

Reputation: 33139

In my opinion, the most painless way to deserialize any JSON is to use the JSON.NET library. See also http://json.codeplex.com.

EDIT: Also see this other question on Stack Overflow: How to deserialize with JSON.NET?

Upvotes: 4

Tx3
Tx3

Reputation: 6916

See Darin's answer.

I think you easily modify provided source code to match your needs. This is built-in to the .NET framework (System.Web.Script.Serialization), so there are no external dependencies.

Upvotes: 0

epoch
epoch

Reputation: 16615

Check out the C# section at json.org

Upvotes: 0

Related Questions