如何在C#中使用json对象 [英] how to work with json object in c#

查看:1538
本文介绍了如何在C#中使用json对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用来自API的json,这就是我正在谈论的内容:

I'm working with a json which comes from an API, here is what I'm talking about:

{
  "popularity": 3.518962,
  "production_companies": [
    {
      "name": "value1",
      "id": 4
    },
    {
      "name": "value2",
      "id": 562
    },
    {
      "name": "value13",
      "id": 14654
    },
    {
      "name": "value4",
      "id": 19177
    },
    {
      "name": "value5",
      "id": 23243
    }
  ]
}

我已经可以返回popularity

作为示例,我需要知道如何访问name的值以及它是哪个name?

As an example I need to know how can I access value of name and which name it is?

我也试图将其转换为数组,但是没有用,或者我做错了事.

I also tried to convert it to an array but didn't work or I did something wrong.

电影课:

public class Movie {

    public string popularity {get; set;}
    public object production_companies {get; set;}

    public Movie GetBasic(string id) {
        string json = @"{
                      "popularity": 3.518962,
                      "production_companies": [
                        {
                          "name": "value1",
                          "id": 4
                        },
                        {
                          "name": "value2",
                          "id": 562
                        },
                        {
                          "name": "value13",
                          "id": 14654
                        },
                        {
                          "name": "value4",
                          "id": 19177
                        },
                        {
                          "name": "value5",
                          "id": 23243
                        }
                      ]
                    }";

        Movie Data = JsonConvert.DeserializeObject<Movie>(json);

        return Data;

}

到目前为止我所做的:

@{
  var arr = Item.production_companies.ToString().Substring(1, (Item.production_companies.ToString().Length - 2)).ToArray();
  foreach(var a in arr) {
    @a.name
  }
}

推荐答案

获得json字符串后,需要反序列化它. 使用该网站生成模型

After you get a json string you need to deserialize it. Use this site to generate you model

http://json2csharp.com/

您将获得一些类似的课程

you will get some classes like

public class ProductionCompany
{
    public string name { get; set; }
    public int id { get; set; }
}

public class RootObject
{
    public double popularity { get; set; }
    public List<ProductionCompany> production_companies { get; set; }
}

然后您可以致电

var json = "...yout json string..."
RootObject obj = JsonConvert.DeserializeObject<RootObject >(json);

您可以轻松使用检索到的数据

and you can use the data retreived easily

这篇关于如何在C#中使用json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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