Parsing JSON objects to c#
I am trying to use the example in this link http://sharpdevpt.blogsp开发者_高级运维ot.com/2009/10/deserialize-json-on-c.html?showComment=1265045828773#c2497312518008004159
But my project wont compile using JavaScriptConvert.DeserializeObject, the example says this is from a .net library does anyone know which one?
I know the example below uses Newtonsoft.Json....
The Javascript Serializer in .NET is part of the System.Web.Script.Serialization
namespace.
Here's an example extension method I use to deserialize strings:
public static T FromJSON<T>(this string json)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
return jss.Deserialize<T>(json);
}
Since this is an extension method of string
you can use it on any string.
MyCustomType = myJsonString.FromJSON<MyCustomType>();
You might also want to have a look at JSON.NET, which is a free, open-source project, and it's both a lot faster than the built-in .NET JSON serializers, and it's also available on .NET 1.x and 2.0, if you still need to support those.
It's quite a marvellous piece of software indeed! Highly recommended.
The link you posted is from my blog, what's the problem on using it? feel free to reply on the blog post or mail me to ricmrodrigues@gmail.com. I've been using for a while and it works fine.
About the discussed JavascriptSerializer that comes embedded on the .Net Framework, the problem is that this serializer doesn't serialize to/from List<>. If you want to do it you need to use Newtonsoft.JSON to do it, because .NET Framework simply doesn't support it. And since the main use for this is to return JSON to some client-side script, for searching or whatever, the List<> thing is a must.
But with that piece of code you can't deserialize/serialize List<> which are very handy in case you're handling result sets, and are more performant than .NET's built-in.JavascriptSerializer, so the Newtonsoft.Json is the best option:
For a single object of your custom type:
classtype myDeserializedObj = (classtype)JavaScriptConvert.DeserializeObject(jsonString, typeof(classtype));
For a List of objects of your custom type:
List<classtype> myDeserializedObjList = (List<classtype>)Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString, typeof(List<classtype>));
The problem is that Newtonsoft.Json can't handle embedded regex in the string. It thinks that \( is a bad escape sequence. This raises the question: What business is it of Newtonsoft to look inside a quoted string? "...." should tell the converter that the stuff is as is.
For a simple way to deserialize http://blogs.msdn.com/rakkimk/archive/2009/01/30/asp-net-json-serialization-and-deserialization.aspx
JavaScriptSerializer js = new JavaScriptSerializer();
Person p2 = js.Deserialize<classtype>(str);
精彩评论