如何在WinRT中反/序列化JSON?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (13)

如何获取对象并将其转换为JSON字符串,然后再从字符串返回到该对象,特别是在Windows 8 Metro应用程序的WinRT中?

提问于
用户回答回答于

就像这样:

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(); }
    }
}
用户回答回答于

首先用http://json2csharp.com/生成C#类 然后使用http://james.newtonking.com/pages/json-net.aspx进行解析

我的用户类目前看起来像这样:

public class User
{
    public string id { get; set; }
    public string username { get; set; }
    public string full_name { get; set; }
    public string profile_picture { get; set; }
    public string bio { get; set; }
    public string website { get; set; }
    public Counts counts { get; set; }

    public static User SingleFromJSON(string jsonString)
    {
        return JsonConvert.DeserializeObject<SingleUser>(jsonString).data;
    }

    public static User MultipleFromJSON(string jsonString)
    {
        return JsonConvert.DeserializeObject<SingleUser>(jsonString).data;
    }

    private class SingleUser
    {
        public User data { get; set; }
    }

    private class MultipleUsers
    {
        public List<User> data { get; set; }
    }
}

public class Counts
{
    public int media { get; set; }
    public int follows { get; set; }
    public int followed_by { get; set; }
}

扫码关注云+社区