2

I'm trying to keep from depending on open source or third party libraries such as Json.NET to parse incoming JSON from an HttpWebResponse. Why? Because the more reliance on open source frameworks to aid in your implementations, the more your app has to rely on those dependencies...I don't like my apps to be depenent on a lot of libraries for many reasons if at all possible. I'm ok with using stuff like Enterprise Library because it's supported by MS but I'm taking more open source libraries.

Anyway, I'm trying to figure out the best way to parse incoming JSON server-side in .NET 3.5.

I know this is going to get a lot of responses and I've even used the .NET 3.5 JavaScriptSerializer to serialize data to JSON but now I'm trying to figure out the best and most simple way to do the reverse without again, having to use a 3rd party / open source framework to aid in this.

4

1 回答 1

10

Microsoft推荐的JSON 序列化程序是DataContractJsonSerializer此类存在于System.Runtime.Serialization程序集中

该示例演示了将 JSON 数据反序列化为对象。

MemoryStream stream1 = new MemoryStream();     
Person p2 = (Person)ser.ReadObject(stream1);

要将 Person 类型的实例序列化为 JSON,首先创建 DataContractJsonSerializer 并使用 WriteObject 方法将 JSON 数据写入流。

Person p = new Person();
//Set up Person object...
MemoryStream stream1 = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Person));
ser.WriteObject(stream1, p);

更新:添加了 Helper 类

这是一个示例帮助程序类,可用于简单的 To/From Json 序列化:

public static class JsonHelper
{
    public static string ToJson<T>(T instance)
    {
        var serializer = new DataContractJsonSerializer(typeof(T));
        using (var tempStream = new MemoryStream())
        {
            serializer.WriteObject(tempStream, instance);
            return Encoding.Default.GetString(tempStream.ToArray());
        }
    }

    public static T FromJson<T>(string json)
    {
        var serializer = new DataContractJsonSerializer(typeof(T));
        using (var tempStream = new MemoryStream(Encoding.Unicode.GetBytes(json)))
        {
            return (T)serializer.ReadObject(tempStream);
        }
    }
}
于 2010-08-02T20:10:20.113 回答