在解析JSON数组在C#中的类 [英] Parse a Json Array in to a class in c#

查看:148
本文介绍了在解析JSON数组在C#中的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我分析这个单一的JSON:

I parsed this single Json :

{
    "text": "Sample Text",
    "id": 123456789,
    "user": {
      "name": "ExampleUser",
      "id": 123,
      "screen_name": "ExampleUser"
    },
    "in_reply_to_screen_name": null,
  }

我的C#类RootObject:

to my c# class RootObject :

public class User
{
    public string name { get; set; }
    public int id { get; set; }
    public string screen_name { get; set; }
}

public class RootObject
{
    public string text { get; set; }
    public long id { get; set; }
    public User user { get; set; }
    public object in_reply_to_screen_name { get; set; }
}

是这样的:

RootObject h = JsonConvert.DeserializeObject<RootObject>(string);

这一切都完美地工作,但现在我想解析所有的precedent JSON对象的数组。

All of this worked perfectly, but now I would like to parse an Array of all the precedent json object.

例如这个JSON数组:

For example this Json Array :

[
    {
    "text": "Sample Text",
    "id": 123456789,
    "user": {
      "name": "ExampleUser",
      "id": 123,
      "screen_name": "ExampleUser"
    },
    "in_reply_to_screen_name": null,
  },
     {
    "text": "Another Sample Text",
    "id": 101112131415,
    "user": {
      "name": "ExampleUser2",
      "id": 124,
      "screen_name": "ExampleUser2"
    },
    "in_reply_to_screen_name": null,
  }
] 

我创建另一个类:

I create another class :

  public class ListRoot { 
      public List<RootObject> status { get; set; } 
  }

和然后用同样的方法

ListRoot h = JsonConvert.DeserializeObject<ListRootObject>(string);

但它不工作。你知道我可以解析此JSON数组到C#类?

But it does not work. Do you know how can I parse this Json array to a c# class?

推荐答案

您的JSON会工作,如果你简单地反序列化作为列表&LT; RootObject&GT;

The JSON you have will work if you simply deserialize it as a List<RootObject>:

var h = JsonConvert.DeserializeObject<List<RootObject>>(string);

或数组:

var h = JsonConvert.DeserializeObject<RootObject[]>(string);

如果你想反序列化 ListRoot 时,JSON就需要这样的:

If you want to deserialize a ListRoot, the JSON would need to look like this:

{
    "status": [
        {
            "text": "Sample Text",
            ...
        },
        {
            "text": "Another Sample Text",
            ...
        }
    ] 
}

这篇关于在解析JSON数组在C#中的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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