Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserializing json to anonymous object in c#

Tags:

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

like image 201
Shawn Mclean Avatar asked Jul 12 '11 22:07

Shawn Mclean


People also ask

How do I deserialize a JSON object?

A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.

How do I make an anonymous object?

You create anonymous types by using the new operator together with an object initializer. For more information about object initializers, see Object and Collection Initializers. The following example shows an anonymous type that is initialized with two properties named Amount and Message .

What is Deserializing a JSON?

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).


2 Answers

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

like image 150
agent-j Avatar answered Oct 25 '22 03:10

agent-j


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;
like image 39
i31nGo Avatar answered Oct 25 '22 04:10

i31nGo