Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How do I take an object and convert it to a JSON string and then back into that object from a string, specifically, in WinRT for my Windows 8 Metro application?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
465 views
Welcome To Ask or Share your Answers For Others

1 Answer

Like this:

using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;

public static T Deserialize<T>(string json)
{
    var _Bytes = Encoding.Unicode.GetBytes(json);
    using (MemoryStream _Stream = new MemoryStream(_Bytes))
    {
        var _Serializer = new DataContractJsonSerializer(typeof(T));
        return (T)_Serializer.ReadObject(_Stream);
    }
}

public static string Serialize(object instance)
{
    using (MemoryStream _Stream = new MemoryStream())
    {
        var _Serializer = new DataContractJsonSerializer(instance.GetType());
        _Serializer.WriteObject(_Stream, instance);
        _Stream.Position = 0;
        using (StreamReader _Reader = new StreamReader(_Stream)) 
        { return _Reader.ReadToEnd(); }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...