Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
497 views
in Technique[技术] by (71.8m points)

c# - How do I de/serialize JSON in WinRT?

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...