Shawn Mclean
Shawn Mclean

Reputation: 57479

Deserializing json to anonymous object in c#

How do I convert a string of json formatted data into an anonymous object?

Upvotes: 21

Views: 38126

Answers (6)

AaA
AaA

Reputation: 3694

Since nobody mentioned SimpleJSON I'm adding it here. It is a small class (below 50k) and you only need to use one of the files (Unity, .NET or Binary) which is impressive comparing NewtonSoft library (currently JSON.NET). It does not require you to include entire C# compiler in your program and it is relatively fast (needed a few tweaks to make it even faster). It has lazy loading too which will not parse the whole JSON when you only need to read part of it.

Parsing is done like this

JSONNode node = JSON.Parse(str)

And accessing content is like so

node["key"].AsString
node["key"].AsInt
node["key"].AsArray   // To access JSON Array
node["key"].AsObject  // To access JSON in key as object
...

Or you can just continue using brackets like so

node["key1"]["key2"]["key3"].AsString

To create a JSON string I would use StringBuilder and generate json string manually, which is the fastest method ever. But if you prefer, you can do it using SimpleJson like so

JSONNode node = new JSONObject();
node["key"]= "some data";
node["key1"] = new JSONObject();
node["key1"]["key2"] = "another data";
String s = node.ToString();

Which will generate json string as following

{
    "key":"somedata",
    "key1": {
        "key2":"another data"
    }
}

Previous versions wouldn't throw exception if key didn't exist and return default value (as defined in C# standard, but current version will throw exception.

Upvotes: 0

Paul Totzke
Paul Totzke

Reputation: 1440

using Newtonsoft.Json, use DeserializeAnonymousType:

string json = GetJsonString();
var anonType = new { Order = new Order(), Account = new Account() };
var anonTypeList = new []{ anonType }.ToList(); //Trick if you have a list of anonType
var jsonResponse = JsonConvert.DeserializeAnonymousType(json, anonTypeList);

Based my answer off of this answer: https://stackoverflow.com/a/4980689/1440321

Upvotes: 2

Horitsu
Horitsu

Reputation: 271

vb.net using Newtonsoft.Json :

dim jsonstring = "..."
dim foo As JObject = JObject.Parse(jsonstring)
dim value1 As JToken = foo("key")


e.g.:
dim jsonstring = "{"MESSAGE":{"SIZE":"123","TYP":"Text"}}"
dim foo = JObject.Parse(jsonstring)
dim messagesize As String = foo("MESSAGE")("SIZE").ToString()
'now in messagesize is stored 123 as String

So you don't need a fixed structure, but you need to know what you can find there.

But if you don't even know what is inside, than you can enumerate thru that JObject with the navigation members e.g. .first(), .next() E.g.: So you could implement a classical depth-first search and screening the JObject

(for converting vb.net to c#: http://converter.telerik.com/)

Upvotes: 1

i31nGo
i31nGo

Reputation: 1502

using dynamics is something like this:

string jsonString = "{\"dateStamp\":\"2010/01/01\", \"Message\": \"hello\" }";
dynamic myObject = JsonConvert.DeserializeObject<dynamic>(jsonString);

DateTime dateStamp = Convert.ToDateTime(myObject.dateStamp);
string Message = myObject.Message;

Upvotes: 16

David Ly
David Ly

Reputation: 31606

I think the closest you can get is dynamic in .NET 4.0

The reason anonymous objects wouldn't work is because they're still statically typed, and there's no way for the compiler to provide intellisense for a class that only exists as a string.

Upvotes: -1

agent-j
agent-j

Reputation: 27943

C# 4.0 adds dynamic objects that can be used. Have a look at this.

Upvotes: 15

Related Questions