反序列化嵌套在数组中的对象

时间:2018-08-07 09:40:54

标签: c# json.net

我正努力反序列化从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"
  }
}

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

任何可能使我步入正轨的指针将不胜感激。

2 个答案:

答案 0 :(得分:0)

这似乎对我来说很好,只是使用动态...

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

您尝试了什么?

答案 1 :(得分:0)

我将为该结构创建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#对象,诸如intellisense和代码完成之类的事情就可以工作。