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.
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.
DeserializeObject can throw several unexpected exceptions (JsonReaderException is the one that is usually expected). These are: ArgumentException.
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).
SerializeObject Method (Object, Type, JsonSerializerSettings) Serializes the specified object to a JSON string using a type, formatting and JsonSerializerSettings. Namespace: Newtonsoft.Json.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With