C# json parsing with Json.NET

本文关键字:Json NET with parsing json | 更新日期: 2023-09-27 18:12:12

我正在使用web API为Steam制作好友列表管理工具。API返回以下JSON:

{
"friendslist": {
    "friends": [
        {
            "steamid": "12345678",
            "relationship": "friend",
            "friend_since": 1290444866
        },
        {
            "steamid": "87654321",
            "relationship": "friend",
            "friend_since": 1421674782
        },
        {
            "steamid": "5287931",
            "relationship": "friend",
            "friend_since": 1418428351
        }
    ]
}

我试着用下面的代码解析它:

public class Friendslist
{
    public IDictionary<int, IDictionary<int, Friend>> friends { get; set; }
}
public class Friend
{
    public uint steamid { get; set; }
    public string relationship { get; set; }
    public uint friend_since { get; set; }
}
        string jsonString;
        Friendslist jsonData;
        WebRequest wr;
        Stream objStream;
        wr = WebRequest.Create(sURL);
        objStream = wr.GetResponse().GetResponseStream();
        StreamReader objReader = new StreamReader(objStream);
        jsonString = objReader.ReadToEnd();
        jsonData = JsonConvert.DeserializeObject<Friendslist>(jsonString);

但jsonData总是空的,当我检查它与调试器

C# json parsing with Json.NET

你的模型应该像

public class Friend
{
    public string steamid { get; set; }
    public string relationship { get; set; }
    public int friend_since { get; set; }
}
public class Friendslist
{
    public List<Friend> friends { get; set; }
}
public class RootObject
{
    public Friendslist friendslist { get; set; }
}

现在可以反序列化为

var root = JsonConvert.DeserializeObject<RootObject>(jsonString);

查看这个有用的网站http://json2csharp.com/