Way to Deserialize JSON from HttpWebResponse without 3rd party frameworks

ぃ、小莉子 提交于 2019-11-27 19:03:57

问题


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.


回答1:


The Microsoft recommended JSON serializer is DataContractJsonSerializer This class exists within the System.Runtime.Serialization assembly

The sample demonstrates deserializing from JSON data into an object.

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

To serialize an instance of the Person type to JSON, create the DataContractJsonSerializer first and use the WriteObject method to write JSON data to a stream.

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

Update: Added Helper class

Here is a sample helper class that you can use for simple To/From Json serialization:

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);
        }
    }
}


来源:https://stackoverflow.com/questions/3391104/way-to-deserialize-json-from-httpwebresponse-without-3rd-party-frameworks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!