Creating model for JSON where key is a value in android

Prabhtej Singh :

I want to create a model from JSON where key is a value. This is the exact issue described, but in iOS. I want a similar solution in Android. Basically I want to have a Decodable equivalent in Android.

I am using GSON to parse JSON to model. As of now, I have compared the JSON key (mentioned in the link) against static values.

JSON :

{  
    "rows" :
    [
        {
            "_id": "5cdc0ede5c3dcb04bdb3a972",
            "emp_code": 187,
            "log_id": 361711,
            "punch_time": "2019-05-07T04:00:33.000Z",
            "pin_type": 1,
            "status": 4,
            "__v": 0
        },
        {
            "_id": "5cdc40de5c3dcb04bdb3a972",
            "emp_code": 111,
            "log_id": 361701,
            "punch_time": "2019-05-07T04:00:35.000Z",
            "pin_type": 101,
            "status": 4,
            "__v": 0
        }
    ],
    "pin_type_text": {
        "1": "In Fingerprint",
        "4": "In Card",
        "101": "Out Fingerprint",
        "104": "Out Card"
    }
}  

The value of pin_type in each row refers to the record in pin_type_text mapped with it's key.

I am using GSON for creating models, and here is the model class :

class MyModel {
    var length : Long = 0
    var rows = ArrayList<Rows>()
    var pin_type_text : String = ""
}

class PinTypeText {
    var 1 : String = ""
    var 4 : String = ""
    var 101 : String = ""
    var 104 : String = ""
  }

Basically, the keys defined in class PinTypeText are the values of the key 'pin_type' obtained in Rows model as seen in the JSON shared. So in this case, the keys in 'PinTypeText' are dependent on values defined in 'rows'. Hence, i want 'PinTypeText' model to be created with respect to 'pin_type' values from 'Rows' model.

Issue : Suppose in future, the 'pin_type' values - 1, 4, 101, 104 change in the backend, how can I handle such a case without changing my model. As per this model structure, I need to change my model class every time the backend model changes

Kou Peto :

you can store the item PinTypeText as a JsonElement and not as a custom class, so your response model will be something like this

public class Response{

@SerializedName("rows")
@Expose
private List<Row> rows = null;
@SerializedName("pin_type_text")
@Expose
private JsonElement pinTypeText;

public List<Row> getRows() {
return rows;
}

public void setRows(List<Row> rows) {
this.rows = rows;
}

public JsonElement getPinTypeText() {
return pinTypeText;
}

public void setPinTypeText(JsonElement pinTypeText) {
this.pinTypeText = pinTypeText;
}

}

and when you want to check the type you can convert it to JsonObject and get the value for the key, example

 pinTypeText=  response.getPinTypeText().asJsonObject().get([your pin_type here]).toString()

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=105249&siteId=1