Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize JSON to anonymous object

Tags:

json

c#

asp.net

In C#, I have successfully serialized an anonymous object into JSON by use of code like this...

var obj = new { Amount = 108, Message = "Hello" }; JavaScriptSerializer serializer = new JavaScriptSerializer(); String output = serializer.Serialize(obj); 

However, what I would like to be able to do later is to deserialize the JSON string back into an anonymous object. Something like this...

var obj2 = serializer.Deserialize(output, object); 

But the serializer.Deserialize() method requires a second parameter that is the type of object it will deserialize to.

I tried this...

var obj2 = serializer.Deserialize(output, obj.GetType()); 

But this produces an error:

No parameterless constructor defined for type of '<>f__AnonymousType0`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'.

I'm not sure what this error means.

like image 388
jdavis Avatar asked Aug 01 '11 21:08

jdavis


People also ask

How do I deserialize JSON to an 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.

Does Jsonconvert DeserializeObject throw?

DeserializeObject can throw several unexpected exceptions (JsonReaderException is the one that is usually expected). These are: ArgumentException.

What is Deserializing 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).

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

how about dynamics, the fastest way I see is this:

dynamic myObject = JsonConvert.DeserializeObject<dynamic>(output);  decimal Amount = Convert.ToDecimal(myObject.Amount); string Message = myObject.Message; 

Note: You will need Newtonsoft.json.dll reference

like image 175
i31nGo Avatar answered Sep 16 '22 16:09

i31nGo