Moshi 是否要求响应中的每个元素都在数据 class 中声明?

Does Moshi require each element in response to be declared in data class?

我正在使用一个 returns 响应如下所示的端点:

{
  "@context": [
    "https://geojson.org/geojson-ld/geojson-context.jsonld",
    {
      "@version": "1.1",
      "wx": "https://api.weather.gov/ontology#",
      "@vocab": "https://api.weather.gov/ontology#"
    }
  ],
  "type": "FeatureCollection",
  "features": [
    {
      "id": "https://api.weather.gov/alerts/urn:oid:2.49.0.1.840.0.8d6d83b7751ab21864264ed4c91782b80017f621.004.1",
      "type": "Feature",
      "geometry": null,
      "properties": {
        "@id": "https://api.weather.gov/alerts/urn:oid:2.49.0.1.840.0.8d6d83b7751ab21864264ed4c91782b80017f621.004.1",
        "@type": "wx:Alert",
        "id": "urn:oid:2.49.0.1.840.0.8d6d83b7751ab21864264ed4c91782b80017f621.004.1",
        "areaDesc": "Lower Clark Fork Region",
        "geocode": {
          "SAME": [
            "030061",
            "030063",
            "030089"
          ],
          "UGC": [
            "MTZ004"
          ]
        },
        "affectedZones": [
          "https://api.weather.gov/zones/forecast/MTZ004"
        ],
        "references": [
          {
            "@id": "https://api.weather.gov/alerts/urn:oid:2.49.0.1.840.0.f4a13cd549ad35c70385947a706b330897c03de7.004.1",
            "identifier": "urn:oid:2.49.0.1.840.0.f4a13cd549ad35c70385947a706b330897c03de7.004.1",
            "sender": "w-nws.webmaster@noaa.gov",
            "sent": "2022-04-11T03:17:00-06:00"
          }
        ],
        "sent": "2022-04-11T15:59:00-06:00",
        "effective": "2022-04-11T15:59:00-06:00",
        "onset": "2022-04-11T17:00:00-06:00",
        "expires": "2022-04-12T06:00:00-06:00",
        "ends": "2022-04-12T06:00:00-06:00",
        "status": "Actual",
        "messageType": "Update",
        "category": "Met",
        "severity": "Severe",
        "certainty": "Likely",
        "urgency": "Expected",
        "event": "High Wind Warning",
        "sender": "w-nws.webmaster@noaa.gov",
        "senderName": "NWS Missoula MT",
        "headline": "High Wind Warning issued April 11 at 3:59PM MDT until April 12 at 6:00AM MDT by NWS Missoula MT",
        "description": "* WHAT...Northeast winds 15 to 35 mph with gusts up to 55 mph\nexpected.\n\n* WHERE...Evaro Hill, Highway 200 Thompson Falls to Plains,\nHighway 200 Trout Creek to Heron, and I-90 Lookout Pass to\nHaugan.\n\n* WHEN...From 5 PM Monday to 6 AM MDT Tuesday.\n\n* IMPACTS...Damaging winds will blow down trees and power lines.\nWidespread power outages are expected. Travel will be\ndifficult, especially for high profile vehicles.",
        "instruction": "People should avoid being outside in forested areas and around\ntrees and branches. If possible, remain in the lower levels of\nyour home during the windstorm, and avoid windows. Use caution if\nyou must drive.",
        "response": "Prepare",
        "parameters": {
          "AWIPSidentifier": [
            "NPWMSO"
          ],
          "WMOidentifier": [
            "WWUS75 KMSO 112159"
          ],
          "NWSheadline": [
            "HIGH WIND WARNING REMAINS IN EFFECT UNTIL 6 AM MDT TUESDAY"
          ],
          "BLOCKCHANNEL": [
            "EAS",
            "NWEM",
            "CMAS"
          ],
          "EAS-ORG": [
            "WXR"
          ],
          "VTEC": [
            "/O.CON.KMSO.HW.W.0002.220411T2300Z-220412T1200Z/"
          ],
          "eventEndingTime": [
            "2022-04-12T12:00:00+00:00"
          ],
          "expiredReferences": [
            "w-nws.webmaster@noaa.gov,urn:oid:2.49.0.1.840.0.608ed2a653603c02dc4d9829b6b5fc0b806ebd6c.005.1,2022-04-10T14:26:00-06:00"
          ]
        }
      }
    },
    {
      "id": "https://api.weather.gov/alerts/urn:oid:2.49.0.1.840.0.8d6d83b7751ab21864264ed4c91782b80017f621.005.1",
      "type": "Feature",
      "geometry": null,
      "properties": {
        "@id": "https://api.weather.gov/alerts/urn:oid:2.49.0.1.840.0.8d6d83b7751ab21864264ed4c91782b80017f621.005.1",
        "@type": "wx:Alert",
        "id": "urn:oid:2.49.0.1.840.0.8d6d83b7751ab21864264ed4c91782b80017f621.005.1",
        "areaDesc": "Missoula/Bitterroot Valleys",
        "geocode": {
          "SAME": [
            "030063",
            "030081"
          ],
          "UGC": [
            "MTZ005"
          ]
        },
        "affectedZones": [
          "https://api.weather.gov/zones/forecast/MTZ005"
        ],
        "references": [
          {
            "@id": "https://api.weather.gov/alerts/urn:oid:2.49.0.1.840.0.f4a13cd549ad35c70385947a706b330897c03de7.005.1",
            "identifier": "urn:oid:2.49.0.1.840.0.f4a13cd549ad35c70385947a706b330897c03de7.005.1",
            "sender": "w-nws.webmaster@noaa.gov",
            "sent": "2022-04-11T03:17:00-06:00"
          }
        ],
        "sent": "2022-04-11T15:59:00-06:00",
        "effective": "2022-04-11T15:59:00-06:00",
        "onset": "2022-04-11T15:59:00-06:00",
        "expires": "2022-04-12T00:00:00-06:00",
        "ends": "2022-04-12T00:00:00-06:00",
        "status": "Actual",
        "messageType": "Update",
        "category": "Met",
        "severity": "Severe",
        "certainty": "Likely",
        "urgency": "Expected",
        "event": "High Wind Warning",
        "sender": "w-nws.webmaster@noaa.gov",
        "senderName": "NWS Missoula MT",
        "headline": "High Wind Warning issued April 11 at 3:59PM MDT until April 12 at 12:00AM MDT by NWS Missoula MT",
        "description": "* WHAT...Northeast winds 25 to 35 mph with gusts up to 55 mph\nexpected in the Missoula Valley. Northeast wind 35 to 45 mph\nwith gusts to 60 mph in the Rattlesnake area. North winds 25\nto 35 mph in the Bitterroot Valley developing late.\n\n* WHERE...Missoula/Bitterroot Valleys.\n\n* WHEN...From 2 PM Monday to midnight MDT Monday night.\n\n* IMPACTS...Damaging winds will blow down trees and power lines.\nWidespread power outages are expected. Travel will be\ndifficult, especially for high profile vehicles.",
        "instruction": "People should avoid being outside in forested areas and around\ntrees and branches. If possible, remain in the lower levels of\nyour home during the windstorm, and avoid windows. Use caution if\nyou must drive.",
        "response": "Prepare",
        "parameters": {
          "AWIPSidentifier": [
            "NPWMSO"
          ],
          "WMOidentifier": [
            "WWUS75 KMSO 112159"
          ],
          "NWSheadline": [
            "HIGH WIND WARNING REMAINS IN EFFECT UNTIL MIDNIGHT MDT TONIGHT"
          ],
          "BLOCKCHANNEL": [
            "EAS",
            "NWEM",
            "CMAS"
          ],
          "EAS-ORG": [
            "WXR"
          ],
          "VTEC": [
            "/O.CON.KMSO.HW.W.0002.000000T0000Z-220412T0600Z/"
          ],
          "eventEndingTime": [
            "2022-04-12T06:00:00+00:00"
          ],
          "expiredReferences": [
            "w-nws.webmaster@noaa.gov,urn:oid:2.49.0.1.840.0.608ed2a653603c02dc4d9829b6b5fc0b806ebd6c.004.1,2022-04-10T14:26:00-06:00"
          ]
        }
      }
    },
    {
      "id": "https://api.weather.gov/alerts/urn:oid:2.49.0.1.840.0.59e9610ae08c49443445b07f260dae1112225a67.004.1",
      "type": "Feature",
      "geometry": null,
      "properties": {
        "@id": "https://api.weather.gov/alerts/urn:oid:2.49.0.1.840.0.59e9610ae08c49443445b07f260dae1112225a67.004.1",
        "@type": "wx:Alert",
        "id": "urn:oid:2.49.0.1.840.0.59e9610ae08c49443445b07f260dae1112225a67.004.1",
        "areaDesc": "Bitterroot/Sapphire Mountains",
        "geocode": {
          "SAME": [
            "030039",
            "030063",
            "030081"
          ],
          "UGC": [
            "MTZ006"
          ]
        },
        "affectedZones": [
          "https://api.weather.gov/zones/forecast/MTZ006"
        ],
        "references": [
          {
            "@id": "https://api.weather.gov/alerts/urn:oid:2.49.0.1.840.0.bfd559e3720f2e662a516c15d4bade5330ab217d.001.2",
            "identifier": "urn:oid:2.49.0.1.840.0.bfd559e3720f2e662a516c15d4bade5330ab217d.001.2",
            "sender": "w-nws.webmaster@noaa.gov",
            "sent": "2022-04-10T14:44:00-06:00"
          },
          {
            "@id": "https://api.weather.gov/alerts/urn:oid:2.49.0.1.840.0.2d28ef3525476dfa6850e893d8aad530ea8db565.002.1",
            "identifier": "urn:oid:2.49.0.1.840.0.2d28ef3525476dfa6850e893d8aad530ea8db565.002.1",
            "sender": "w-nws.webmaster@noaa.gov",
            "sent": "2022-04-10T16:20:00-06:00"
          }
        ],
        "sent": "2022-04-11T01:39:00-06:00",
        "effective": "2022-04-11T01:39:00-06:00",
        "onset": "2022-04-11T15:00:00-06:00",
        "expires": "2022-04-12T01:45:00-06:00",
        "ends": "2022-04-12T12:00:00-06:00",
        "status": "Actual",
        "messageType": "Update",
        "category": "Met",
        "severity": "Severe",
        "certainty": "Likely",
        "urgency": "Expected",
        "event": "Winter Storm Warning",
        "sender": "w-nws.webmaster@noaa.gov",
        "senderName": "NWS Missoula MT",
        "headline": "Winter Storm Warning issued April 11 at 1:39AM MDT until April 12 at 12:00PM MDT by NWS Missoula MT",
        "description": "* WHAT...Heavy snow expected. Total snow accumulations of 8 to 14\ninches Sula to Lost Trail Pass and 4 to 7 inches at Lolo Pass.\nNortherly winds gusting as high as 35 mph will produce blowing\nand drifting snow at times.\n\n* WHERE...Bitterroot/Sapphire Mountains.\n\n* WHEN...From 3 PM this afternoon to noon MDT Tuesday.\n\n* IMPACTS...Travel could be very difficult. Patchy blowing snow\ncould significantly reduce visibility. The cold wind chills as\nlow as 15 below zero could result in hypothermia if precautions\nare not taken.",
        "instruction": "If you must travel, keep an extra flashlight, food, and water in\nyour vehicle in case of an emergency.\n\nThe latest road conditions for the state you are calling from can\nbe obtained by calling 5 1 1.",
        "response": "Prepare",
        "parameters": {
          "AWIPSidentifier": [
            "WSWMSO"
          ],
          "WMOidentifier": [
            "WWUS45 KMSO 110739"
          ],
          "NWSheadline": [
            "WINTER STORM WARNING NOW IN EFFECT FROM 3 PM THIS AFTERNOON TO NOON MDT TUESDAY"
          ],
          "BLOCKCHANNEL": [
            "EAS",
            "NWEM",
            "CMAS"
          ],
          "EAS-ORG": [
            "WXR"
          ],
          "VTEC": [
            "/O.EXT.KMSO.WS.W.0007.220411T2100Z-220412T1800Z/"
          ],
          "eventEndingTime": [
            "2022-04-12T18:00:00+00:00"
          ]
        }
      }
    },
    {
      "id": "https://api.weather.gov/alerts/urn:oid:2.49.0.1.840.0.59e9610ae08c49443445b07f260dae1112225a67.008.1",
      "type": "Feature",
      "geometry": null,
      "properties": {
        "@id": "https://api.weather.gov/alerts/urn:oid:2.49.0.1.840.0.59e9610ae08c49443445b07f260dae1112225a67.008.1",
        "@type": "wx:Alert",
        "id": "urn:oid:2.49.0.1.840.0.59e9610ae08c49443445b07f260dae1112225a67.008.1",
        "areaDesc": "Missoula/Bitterroot Valleys",
        "geocode": {
          "SAME": [
            "030063",
            "030081"
          ],
          "UGC": [
            "MTZ005"
          ]
        },
        "affectedZones": [
          "https://api.weather.gov/zones/forecast/MTZ005"
        ],
        "references": [],
        "sent": "2022-04-11T01:39:00-06:00",
        "effective": "2022-04-11T01:39:00-06:00",
        "onset": "2022-04-11T15:00:00-06:00",
        "expires": "2022-04-12T01:45:00-06:00",
        "ends": "2022-04-12T09:00:00-06:00",
        "status": "Actual",
        "messageType": "Alert",
        "category": "Met",
        "severity": "Moderate",
        "certainty": "Likely",
        "urgency": "Expected",
        "event": "Winter Weather Advisory",
        "sender": "w-nws.webmaster@noaa.gov",
        "senderName": "NWS Missoula MT",
        "headline": "Winter Weather Advisory issued April 11 at 1:39AM MDT until April 12 at 9:00AM MDT by NWS Missoula MT",
        "description": "* WHAT...Snow expected. Total snow accumulations of around one\ninch in Missoula, 1 to 3 inches Lolo to Victor, and 4 to 8\ninches Hamilton to Conner.\n\n* WIND...Northeast winds 25 to 35 mph with gusts up to 55 mph\nexpected in the Missoula Valley. Northeast wind 35 to 45 mph\nwith gusts to 60 mph in the Rattlesnake area. North winds 25 to\n35 mph in the Bitterroot Valley Monday night into Tuesday\nmorning.\n\n* WHERE...Missoula/Bitterroot Valleys.\n\n* WHEN...From 3 PM this afternoon to 9 AM MDT Tuesday.\n\n* IMPACTS...Travel could be affected. Patchy blowing snow could\nsignificantly reduce visibility.",
        "instruction": "Slow down and use caution while traveling.\n\nThe latest road conditions for the state you are calling from can\nbe obtained by calling 5 1 1.",
        "response": "Execute",
        "parameters": {
          "AWIPSidentifier": [
            "WSWMSO"
          ],
          "WMOidentifier": [
            "WWUS45 KMSO 110739"
          ],
          "NWSheadline": [
            "WINTER WEATHER ADVISORY IN EFFECT FROM 3 PM THIS AFTERNOON TO 9 AM MDT TUESDAY"
          ],
          "BLOCKCHANNEL": [
            "EAS",
            "NWEM",
            "CMAS"
          ],
          "VTEC": [
            "/O.EXB.KMSO.WW.Y.0024.220411T2100Z-220412T1500Z/"
          ],
          "eventEndingTime": [
            "2022-04-12T15:00:00+00:00"
          ]
        }
      }
    },
    {
      "id": "https://api.weather.gov/alerts/urn:oid:2.49.0.1.840.0.59e9610ae08c49443445b07f260dae1112225a67.009.1",
      "type": "Feature",
      "geometry": null,
      "properties": {
        "@id": "https://api.weather.gov/alerts/urn:oid:2.49.0.1.840.0.59e9610ae08c49443445b07f260dae1112225a67.009.1",
        "@type": "wx:Alert",
        "id": "urn:oid:2.49.0.1.840.0.59e9610ae08c49443445b07f260dae1112225a67.009.1",
        "areaDesc": "Potomac/Seeley Lake Region",
        "geocode": {
          "SAME": [
            "030039",
            "030047",
            "030063",
            "030077"
          ],
          "UGC": [
            "MTZ043"
          ]
        },
        "affectedZones": [
          "https://api.weather.gov/zones/forecast/MTZ043"
        ],
        "references": [
          {
            "@id": "https://api.weather.gov/alerts/urn:oid:2.49.0.1.840.0.2d28ef3525476dfa6850e893d8aad530ea8db565.004.1",
            "identifier": "urn:oid:2.49.0.1.840.0.2d28ef3525476dfa6850e893d8aad530ea8db565.004.1",
            "sender": "w-nws.webmaster@noaa.gov",
            "sent": "2022-04-10T16:20:00-06:00"
          }
        ],
        "sent": "2022-04-11T01:39:00-06:00",
        "effective": "2022-04-11T01:39:00-06:00",
        "onset": "2022-04-11T18:00:00-06:00",
        "expires": "2022-04-12T01:45:00-06:00",
        "ends": "2022-04-12T09:00:00-06:00",
        "status": "Actual",
        "messageType": "Update",
        "category": "Met",
        "severity": "Moderate",
        "certainty": "Likely",
        "urgency": "Expected",
        "event": "Winter Weather Advisory",
        "sender": "w-nws.webmaster@noaa.gov",
        "senderName": "NWS Missoula MT",
        "headline": "Winter Weather Advisory issued April 11 at 1:39AM MDT until April 12 at 9:00AM MDT by NWS Missoula MT",
        "description": "* WHAT...Snow expected. Total snow accumulations of up to two\ninches, with winds gusting as high as 45 mph along highway 200\nand in the Seeley Lake region. Along I-90 from Bonner to\nBearmouth, up to 4 inches is expected, along with wind gusts as\nhigh as 50 mph in isolated areas. Blowing snow will greatly\nreduce visibility along the interstate.\n\n* WHERE...Highway 200 Bonner to Greenough, Highway 83 Seeley\nLake to Condon, and I-90 East Missoula to Bearmouth.\n\n* WHEN...From 6 PM this evening to 9 AM MDT Tuesday.\n\n* IMPACTS...Travel could be affected. Areas of blowing snow could\nsignificantly reduce visibility.",
        "instruction": "Slow down and use caution while traveling.\n\nThe latest road conditions for the state you are calling from can\nbe obtained by calling 5 1 1.",
        "response": "Execute",
        "parameters": {
          "AWIPSidentifier": [
            "WSWMSO"
          ],
          "WMOidentifier": [
            "WWUS45 KMSO 110739"
          ],
          "NWSheadline": [
            "WINTER WEATHER ADVISORY NOW IN EFFECT FROM 6 PM THIS EVENING TO 9 AM MDT TUESDAY"
          ],
          "BLOCKCHANNEL": [
            "EAS",
            "NWEM",
            "CMAS"
          ],
          "VTEC": [
            "/O.EXT.KMSO.WW.Y.0024.220412T0000Z-220412T1500Z/"
          ],
          "eventEndingTime": [
            "2022-04-12T15:00:00+00:00"
          ]
        }
      }
    }
  ],
  "title": "current watches, warnings, and advisories for Missoula County (MTC063) MT",
  "updated": "2022-04-11T22:00:35+00:00"
}

但我只对键 headlinedescriptionresponse 的值感兴趣。这些所需的键嵌套在多个对象中,从我目前所读的内容来看,这些对象至少必须在数据 classes.

中进行描述

是否有必要将整个响应中的每个键都映射到数据中的一个属性class?如果是这样,我不确定如何处理下面的数组:

  "@context": [
    "https://geojson.org/geojson-ld/geojson-context.jsonld",
    {
      "@version": "1.1",
      "wx": "https://api.weather.gov/ontology#",
      "@vocab": "https://api.weather.gov/ontology#"
    }

此数组包含一个 String 和一个 JSON 对象。我如何在我的数据中声明这样的属性 class?

@Json(name = "@context") val context: List<String> // will JSON object be deserialized into a string? 

编辑:我添加了以下数据 classes 以匹配响应:

data class Alert (
    @Json(name = "@context") val context: List<String>,
    val type: String,
    val features: List<AlertFeature>,
    val title: String,
    val updated: String
    )

data class AlertFeature(
    val id: String,
    val type: String,
    val geometry: String,
    val properties: List<AlertProperties>,
)

data class AlertProperties(
    @Json(name = "@id") val fullId: String,
    @Json(name = "@type") val type: String,
    val id: String,
    val areaDesc: String,
    val geocode: Geocode,
    val affectedZones: List<String>,
    val references: List<com.harr1424.privateweather.network.Reference>,
    val sent: String,
    val effective: String,
    val onset: String,
    val expires: String,
    val ends: String,
    val status: String,
    val messageType: String,
    val category: String,
    val severity: String,
    val certainty: String,
    val urgency: String,
    val event: String,
    val sender: String,
    val senderName: String,
    val headline: String,
    val description: String,
    val instruction: String,
    val response: String,
    val parameters: List<Parameter>
)

data class Geocode(
    val SAME: List<String>,
    val UGC: List<String>
)

data class Reference(
    @Json(name = "@id") val id: String,
    val identifier: String,
    val sender: String,
    val sent: String
)

data class Parameter(
    val AWIPSidentifier: List<String>,
    val WMOidentifier: List<String>,
    val BLOCKCHANNEL: List<String>,
    @Json(name = "EAS-ORG") val EASORG: List<String>,
    val VTEC: List<String>,
    val eventEndingTime: List<String>,
    val expiredReferences: List<String>
)

但我仍然不确定如何访问我感兴趣的特定密钥:

interface nwsAlerts {
    @GET("/alerts/active/zone/MTC063")
    suspend fun getALerts(): List<AlertFeature>
}

结果为 com.squareup.moshi.JsonDataException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at path $ 我明白为什么会出现此错误,Moshi 需要一个 JSON 数组,但收到一个 Alert 对象。如何指示 Moshi 在 features 数组开始反序列化?

它所说的是 JSON 对象中的某处,它告诉您需要一个列表,但是您在 DTO 模型中声明它作为一个对象开始,您的代码很好但是它需要一些检查。确保您使用 JSON 对象并查看 LogCat 哪条路径给您带来了问题。检查并使用户端真正清楚的最好方法是转到此 link: https://codebeautify.org/jsonviewer

复制并粘贴 JSON 代码,您将看到哪个区域是对象“{}”或 list/array“[]”。一定要仔细一一检查。

关于你的问题的另一件事是你是否想要所有这些数据,而不是获取必要的代码,我建议你查找事物的域层,因为域模型是从网络 DTO 映射的模型,在这里查找,以便您仅映射您想要获取或需要获取的数据:https://developer.android.com/jetpack/guide/domain-layer