反序列化JSON字符串嵌套字典

时间:2014-02-21 15:24:47

标签: c# json serialization json.net restsharp

我正在尝试使用Riot games REST API在C#中创建一个webapp。我可以使用RESTSharp发出请求,但使用JSON.Net将返回的Json转换为对象时遇到了一些问题。我的请求返回一个JSON字符串,例如:

{\"dyrus\":{\"id\":4136713,\"name\":\"Dyrus\",\"profileIconId\":23,\"summonerLevel\":1,\"revisionDate\":1376908220000}}

我想将其反序列化为具有属性的对象:idnameprofileIconIDsummonerLevelrevisionDate

我遇到的问题是信息被反序列化为字符串,因为字典是嵌套的。检索字符串的嵌套Dictionary部分的最佳方法是什么:{\"id\":4136713,\"name\":\"Dyrus\",\"profileIconId\":23,\"summonerLevel\":1,\"revisionDate\":1376908220000}并将其转换为对象?

感谢您的帮助!

编辑:

以下是我的尝试:

public class LeagueUser
{
    public LeagueUser(string json)
    {
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        string jsonString = (string)serializer.DeserializeObject(json);
        LeagueUser test = (LeagueUser)serializer.DeserializeObject(jsonString);
    }
    public int id { get; set; }
    public string name { get; set; }
    public long revisionDate { get; set; }
}

2 个答案:

答案 0 :(得分:1)

您不需要构造函数,请将LeagueUser类更改为此

public class LeagueUser
{
    public int id { get; set; }
    public string name { get; set; }
    public long revisionDate { get; set; }
}

并使用Json.NET将json反序列化为Dictionary<string, LeagueUser>

string jsonStr = "{\"dyrus\":{\"id\":4136713,\"name\":\"Dyrus\",\"profileIconId\":23,\"summonerLevel\":1,\"revisionDate\":1376908220000}}";

var deserializedObject = JsonConvert.DeserializeObject<Dictionary<string, LeagueUser>>(jsonStr);

您可以通过这种方式获取LeagueUser对象

LeagueUser leagueUser = deserializedObject["dyrus"];

答案 1 :(得分:1)

您可以通过为LeagueUser课程创建自定义转换器来实现您的目标:

public class LeagueUserConverter : JsonConverter
{

    public override bool CanConvert(Type objectType)
    {
        return typeof(LeagueUser) == objectType;
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (!CanConvert(objectType)) return null;

        var jObject = JObject.Load(reader);

        var user = new LeagueUser
            {
                Id = Convert.ToInt64(jObject["dyrus"]["id"]),
                Name = jObject["dyrus"]["name"].ToString(),
                ProfileIconId = Convert.ToInt32(jObject["dyrus"]["profileIconId"]),
                SummonerLevel = Convert.ToInt32(jObject["dyrus"]["summonerLevel"]),
                RevisionDate = Convert.ToInt64(jObject["dyrus"]["revisionDate"])
            };

        return user;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

接下来,您需要使用定义的转换器装饰您的类:

[JsonConverter(typeof(LeagueUserConverter))]
public class LeagueUser
{
    public long Id { get; set; }

    public string Name { get; set; }

    public int ProfileIconId { get; set; }

    public int SummonerLevel { get; set; }

    public long RevisionDate { get; set; }
}

无论您需要何处,请致电DeserializeObject方法:

var user = JsonConvert.DeserializeObject<LeagueUser>(json);

其中json变量是您在问题中发布的json字符串。