【问题标题】:Deserialize objects nested within an array [duplicate]反序列化嵌套在数组中的对象[重复]
【发布时间】:2019-01-14 08:33:13
【问题描述】:

我正在努力反序列化从 API 接收的以下 JSON 字符串:

{
  "appointment_types": [
    {
      "id": 279148,
      "max_attendees": 1,
      "name": "Follow up",
      "billable_item": {
        "links": {
          "self": "https://api.cliniko.com/v1/billable_items/485545"
        }
      },
      "practitioners": {
        "links": {
          "self": "https://api.cliniko.com/v1/appointment_types/279148/practitioners"
        }
      }
    },
    {
      "id": 279149,
      "max_attendees": 1,
      "name": "Assessment",
      "billable_item": {
        "links": {
          "self": "https://api.cliniko.com/v1/billable_items/490437"
        }
      },
      "practitioners": {
        "links": {
          "self": "https://api.cliniko.com/v1/appointment_types/279149/practitioners"
        }
      }
    }
  ],
  "total_entries": 17,
  "links": {
    "self": "https://api.cliniko.com/v1/appointment_types?page=1"
  }
}

我已经搜索过,但找不到适用于上述内容的任何内容。

任何可能让我走上正轨的指针将不胜感激。

【问题讨论】:

标签: c# json.net


【解决方案1】:

这对我来说似乎只使用动态...

dynamic d = JObject.Parse(json);
var totalNumber = d.total_entries.ToString();
var theId = d.appointment_types[0].id.ToString();

你试过什么?

【讨论】:

  • 太棒了!这正是我所需要的。
【解决方案2】:

我会为结构创建 c# 类,然后使用 Newtonsoft Json.NET 进行反序列化。 (它很快并且已经在 c# 中,但您必须添加引用。)

这是我的代码:

class Program
{
    static void Main(string[] args)
    {
        string json = File.ReadAllText("demo.json"); //Your json here
        RequestResult requestResult = Newtonsoft.Json.JsonConvert.DeserializeObject<RequestResult>(json); //There is your result
        Console.WriteLine("Done!");
        Console.ReadLine();
    }
}

class RequestResult
{
    public AppointmentType[] appointment_types;
    public int total_entries;
    public Link links;
}

class Practitioners
{
    public Link links;
}

class BillableItem
{
    public Link links;
}

class Link
{
    public string self;
}

class AppointmentType
{
    public int id;
    public int max_attendees;
    public string name;
    public BillableItem billable_item;
    public Practitioners practitioners;
}

然后你得到一个 c# 对象的结果,像智能感知和代码完成这样的东西就可以工作了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 2018-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多