如何在c#中从Json数组中获取数据?

时间:2018-06-10 15:34:44

标签: c# json

我想从这个JSON数组中获取数据。 我使用了一些关键字,但我每次都会收到错误,如何获取数据?

JArray test1 = JArray.Parse(jsondata);
string ids = test1["id"];

如果我写" id"所以我没有得到答案11

{[
  {
    "id": 11,
    "userName": null,
    "passWord": null,
    "email": "someone@gmail.com",
    "mobile": "9898989898",
    "fullName": "Ramesh Sharma",
    "location": "Rajkot",
    "city_id": 1
  }
]}

2 个答案:

答案 0 :(得分:1)

在对您的问题的评论中,您说您的JSON是:

[
  {
    "id": 11,
    "userName": null,
    "passWord": null,
    "email": "someone@gmail.com",
    "mobile": "9898989898",
    "fullName": "Ramesh Sharma",
    "location": "Rajkot",
    "city_id": 1
  }
]

为您的JSON创建C#类,如here所示,您将获得这些类:

public class Rootobject
{
    public Class1[] Property1 { get; set; }
}

public class Class1
{
    public int id { get; set; }
    public object userName { get; set; }
    public object passWord { get; set; }
    public string email { get; set; }
    public string mobile { get; set; }
    public string fullName { get; set; }
    public string location { get; set; }
    public int city_id { get; set; }
}

然后将其反序列化:

var results = JsonConvert.DeserializeObject<RootObject>(yourJSON);

答案 1 :(得分:1)

你可以得到这样的每个值,然后你需要选择哪个值。

    foreach (JObject content in test1.Children<JObject>())
    {
          string Id = content["id"].ToString();
          string email = content["email"].ToString();
    }

顺便说一句,下面是你正确格式化的Json。

[{"id":11,"userName":null,"passWord":null,"email":"someone@gmail.com","mobile":"9423422882","fullName":"Ramesh Sharma","location":"Rajkot","city_id":1}]