如何在 C# 中反序列化 json 对象数组?这是我的 json:
[{"id":"255521115", "user":"username","userinfo":{"id":"158","online":"false"}}]
我有这个代码来获取用户名:
[JsonProperty("user")]
public string Username { get; set; }
如何获取用户信息的值?我想要 userinfo 对象中的在线值。
最佳答案
VS2013 中有一项很酷的功能。如果您将 JSON 复制到剪贴板并在 Visual Studio 中单击 EDIT -> Paste Special -> Paste JSON as Classes
,它将为您生成类结构。如果需要,您只需重命名一些属性。在您的情况下,类的修改版本将是:
public class Obj
{
public string Id { get; set; }
[JsonProperty("User")]
public string UserName { get; set; }
public Userinfo Userinfo { get; set; }
}
public class Userinfo
{
public string Id { get; set; }
public string Online { get; set; }
}
然后您可以轻松反序列化您的 JSON 字符串:
var json = @"[{""id"":""255521115"", ""user"":""username"",""userinfo"":{""id"":""158"",""online"":""false""}}]";
var objs = JsonConvert.DeserializeObject<IList<Obj>>(json);
关于c# - 反序列化 json 对象数组,其中包含 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29473886/