如何将Json对象转换为C#类对象

时间:2019-03-08 07:31:59

标签: .net json c#-4.0

{
    "users": [
        {
            "name": "User1",
            "email": "support@korewireless.com",
            "phone": "+12049987456",
            "status": "Active",
            "title": "Mr"
        },
        {
            "name": "User2",
            "email": "info@korewireless.com",
            "phone": "+12040147456",
            "status": "Active",
            "title": "Mr"
        },
        {
            "name": "User3",
            "email": "help@korewireless.com",
            "phone": "+12040787456",
            "status": "Active",
            "title": "Ms"
        }
    ]
}

尝试将此json对象转换为列表,但仅具有空值

var a = JsonConvert.DeserializeObject<User>(jsonData);

我如何将其解析为类对象?

3 个答案:

答案 0 :(得分:2)

如果要反序列化特定的json字符串,则需要定义一个包含用户列表的根对象。

例如:

public class ListRoot
{ 
    public List<User> users { get; set; }
}

public class User
{ 
    public string name { get; set; }
    public string phone { get; set; }
    public string email { get; set; }
    public string status { get; set; }
    public string title { get; set; }
}

现在您可以致电

var data = JsonConvert.DeserializeObject<ListRoot>(jsonData);
foreach (User u in data.users)
{
    Console.WriteLine($"User:name={u.name}, phone={u.phone}, email={u.email}");
}

当然,如果您可以控制json数据的产生,则可以使用更简单的方法来准备json数据

[
    {
        "name": "User1",
        "email": "support@korewireless.com",
        "phone": "+12049987456",
        "status": "Active",
        "title": "Mr"
    },
    {
        "name": "User2",
        "email": "info@korewireless.com",
        "phone": "+12040147456",
        "status": "Active",
        "title": "Mr"
    },
    {
        "name": "User3",
        "email": "help@korewireless.com",
        "phone": "+12040787456",
        "status": "Active",
        "title": "Ms"
    }
]

使您能够直接致电

List<User> users = JsonConvert.DeserializeObject<List<User>>(jsonData);

答案 1 :(得分:1)

您应该转换为对象列表,因为您的json是用户对象的枚举。 例如: var a = JsonConvert.DeserializeObject<List<User>>(jsonData);

答案 2 :(得分:1)

这取决于您的User类。请提供代码。

您的json看起来更像List<User>的表示形式。如果是这样,则必须通过JsonConvert.DeserializeObject<List<User>>(json)反序列化。