John Harrington
John Harrington

Reputation: 1727

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

I am working with an endpoint that returns a response like the one below:

{
  "@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": "[email protected]",
            "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": "[email protected]",
        "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": [
            "[email protected],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": "[email protected]",
            "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": "[email protected]",
        "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": [
            "[email protected],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": "[email protected]",
            "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": "[email protected]",
            "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": "[email protected]",
        "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": "[email protected]",
        "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": "[email protected]",
            "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": "[email protected]",
        "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"
}

But I am only interested in the values for keys headline, description, and response. These desired keys are nested inside multiple objects, and from what I have read so far at a minimum these objects must be described in data classes.

Is it necessary that each key in the entire response be mapped to an attribute in a data class? And if so, I am unsure how to handle the array below:

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

This array contains a String and a JSON object. How would I declare such an attribute in my data class?

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

EDIT: I've added the following data classes to match the response:

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>
)

But I am still not sure how to access the specific keys I am interested in:

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

Results in com.squareup.moshi.JsonDataException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at path $ I understand why this error is occurring, Moshi expects a JSON array but receives an Alert object. How is it possible to instruct Moshi to begin deserialization at the features array?

Upvotes: 0

Views: 316

Answers (1)

Georgi Tasev
Georgi Tasev

Reputation: 54

What it states is somewhere within the JSON Object is telling you that is expecting a List of something, however you declared within the DTO model that it begins as an object, you're code is fine but it needs some check up. Make sure you use the JSON Object and taking a look of the LogCat which path gives you the problem. The best way to check and making it really clearly to the user side is to go to this link: https://codebeautify.org/jsonviewer

Copy and paste the JSON code in there and you'll see which area is an object "{}" or a list/array "[]". Make sure you check them one by one carefully.

Another thing about your question is whether or not you want all that data, instead of getting the necessary code, what I suggest is you look up the Domain Layer of things, because the Domain Model is mapped from the Network DTO Model, look it up in here, in order for you to map only the data you want to get or necessary to get: https://developer.android.com/jetpack/guide/domain-layer

Upvotes: 1

Related Questions