如何映射JSON响应自定义类对象 [英] How to map JSON response to custom class object

查看:167
本文介绍了如何映射JSON响应自定义类对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我打电话使用C#的API unirest.io 。我获得以下JSON响应(如 response.Body 的)。

I am calling an API in C# using unirest.io. I get following JSON response (as response.Body).

{
    "persons": [{
        "id": "a010",
        "name": "Joe",
        "subjects": [
            "Math",
            "English"
        ]
    },
    {
        "id": "b020",
        "name": "Jill",
        "subjects": [
            "Science",
            "Arts"
        ]
    }]
}

我想这个如下映射到我的自定义类的对象。

I tried to map this to my custom class object as follows.

HttpRequest request = Unirest.get(API_V1_URL).header("accept", "application/json");
HttpResponse<string> response = request.asString();
var serializer = new JavaScriptSerializer();
persons = serializer.Deserialize<Persons>(response.Body);



但它总是通过设置通过的 persons.infos = NULL 的;

我的自定义类

public class Persons
{
    public PersonInfo[] infos;
}

public class PersonInfo
{
    public string id;
    public string name;
    public string[] subjects;
}

请帮助我我怎么能这样正确映射JSON我的.NET类对象?

Please assist me how can I correctly map such JSON to my .Net class objects ?

推荐答案

反序列化< T> 而不是厂商

persons = serializer.Deserialize<Persons>(response.Body);



重命名属性。

Rename property

public PersonInfo[] infos;

public PersonInfo[] persons;

此外,我会建议你使用自动属性。即

Additionally, I would recommend you to use Auto-properties. i.e.

public PersonInfo[] persons{get;set;}

这篇关于如何映射JSON响应自定义类对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆