使用内部的json对象反序列化json对象的数组

使用内部的json对象反序列化json对象的数组

本文介绍了使用内部的json对象反序列化json对象的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在C#中反序列化json对象数组?这是我的json:

How can I deserialize array of json objects in c#? Here's my json:

[{"id":"255521115", "user":"username","userinfo":{"id":"158","online":"false"}}]

我有以下代码来获取用户名:

I have this code to get username:

 [JsonProperty("user")]
 public string Username { get; set; }

如何获取userinfo的值?我想要userinfo对象内部的在线值.

How can I get values of the userinfo? I want online value that is inside userinfo object.

推荐答案

VS2013中有一项很酷的功能.如果将JSON复制到剪贴板,然后在Visual Studio中单击EDIT -> Paste Special -> Paste JSON as Classes,它将为您生成类结构.您只需要重命名某些属性即可.在您的情况下,类的修改版本将是:

There is one cool feature in VS2013. If you copy your JSON to clipboard and in Visual Studio click EDIT -> Paste Special -> Paste JSON as Classes it will generate class structure for you. All you need is to rename some properties if you want to. In your case modified version of classes will be:

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字符串:

And then you can easily deserialize your JSON string:

var json = @"[{""id"":""255521115"", ""user"":""username"",""userinfo"":{""id"":""158"",""online"":""false""}}]";
var objs = JsonConvert.DeserializeObject<IList<Obj>>(json);

这篇关于使用内部的json对象反序列化json对象的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 10:32