Home > Software design >  Dynamic data class variables : Kotlin , Android
Dynamic data class variables : Kotlin , Android

Time:10-06

This is my JSON API response.

{
    "element_count": 25,
    "near_earth_objects": {
        "2015-09-08": [{
                "id": "2465633",
                "neo_reference_id": "2465633",
                "name": "465633 (2009 JR5)",
                "nasa_jpl_url": "http://ssd.jpl.nasa.gov/sbdb.cgi?sstr=2465633",
                "absolute_magnitude_h": 20.36,
                "estimated_diameter": {
                    ...
                },
                "is_potentially_hazardous_asteroid": true,
                "close_approach_data": [{
                    "close_approach_date": "2015-09-08",
                    "close_approach_date_full": "2015-Sep-08 20:28",
                    "epoch_date_close_approach": 1441744080000,
                    "relative_velocity": {
                        ...
                    },
                    "miss_distance": {
                    ...
                    },
                    "orbiting_body": "Earth"
                }],
                "is_sentry_object": false
            },  
        ],
        "2015-09-07": [{
                "id": "2440012",
                "neo_reference_id": "2440012",
                "name": "440012 (2002 LE27)",
                "nasa_jpl_url": "http://ssd.jpl.nasa.gov/sbdb.cgi?sstr=2440012",
                "absolute_magnitude_h": 19.3,
                "estimated_diameter": {
                    
                },
                "is_potentially_hazardous_asteroid": false,
                "close_approach_data": [{
                    
                    },
                    "miss_distance": {
                        
                    },
                    "orbiting_body": "Earth"
                }],
                "is_sentry_object": false
            },
            
        ]
    }
}

There is an object inside the variable 'near_earth_object'. That date is supposed to be an input from the user.

Since it is dynamic, how do I create a data class of that object? I can create the object 'near_earch_object' as a list, but of objects with those variables inside the date.

But how do I get the date then?

Basically, can someone explain How to create data class of this JSON.

CodePudding user response:

Since you don't know the dates beforehand, you can't create properties for them, you will have to use a map here.

data class ApiResponse(
    @SerializedName("element_count")
    val elementCount: Int,
    @SerializedName("near_earth_objects")
    val nearEarthObjects: Map<String, List<NearEarthObject>>
)

data class NearEarthObject(
    val id: String,
    val name: String,
    ...
)
  • Related