代码之家  ›  专栏  ›  技术社区  ›  David Thielen

如何将JSON内部数组转换为对象数组?

  •  0
  • David Thielen  · 技术社区  · 1 年前

    我尝试了以下代码:

    dynamic result = JsonConvert.DeserializeObject(response.Content!);
    var jsonArray = result.items;
    var arrayEvents = JsonConvert.DeserializeObject<VanEvent[]>(jsonArray);
    

    获取此JSON中的对象数组( response.Content ):

    {
      "items": [
        {
          "eventId": 408936,
          "name": "Door to door",
          "shortName": "door",
          "description": "walking the beat",
          "startDate": "2024-04-17T12:00:00-06:00",
          "endDate": "2024-04-17T15:30:00-06:00",
          "eventType": {
            "eventTypeId": 659466,
            "name": "Canvassing"
          },
          "isOnlyEditableByCreatingUser": false,
          "isPubliclyViewable": null,
          "locations": [],
          "codes": [],
          "notes": [],
          "shifts": [
            {
              "eventShiftId": 461796,
              "name": "Single Shift",
              "startTime": "2024-04-17T12:00:00-06:00",
              "endTime": "2024-04-17T15:30:00-06:00"
            }
          ],
          "roles": [
            {
              "roleId": 567170,
              "name": "Organizer",
              "isEventLead": false,
              "min": null,
              "max": null,
              "goal": null
            },
            {
              "roleId": 567171,
              "name": "Volunteer",
              "isEventLead": false,
              "min": null,
              "max": null,
              "goal": null
            }
          ],
          "ticketCategories": null,
          "voterRegistrationBatches": null,
          "createdDate": "2024-04-15T16:57:00Z",
          "districtFieldValue": null,
          "financialProgram": null,
          "isActive": true,
          "dotNetTimeZoneId": "Mountain Standard Time"
        },
        {
          "eventId": 422483,
          // ...
    

    但呼吁 DeserializeObject() 正在投掷a RuntimeBinderException 带有以下信息:

    The best overloaded method match for 'Newtonsoft.Json.JsonConvert.DeserializeObject<ThirdPartyServices.VAN.VanEvent[]>(string)' has some invalid arguments
    

    为什么?这是在传递这些对象的数组。是的, VanEvent 具有无参数构造函数。

    1 回复  |  直到 1 年前
        1
  •  0
  •   Brian Rogers    1 年前

    我认为你得到这个错误是因为 JsonConvert.DeserializeObject<T>() 需要一个字符串,但您传递给它的是之前反序列化的对象,可能是 JArray .

    请尝试以下操作:

    var result = JObject.Parse(response.Content!);
    var arrayEvents = result["items"].ToObject<VanItem[]>();