简体   繁体   中英

retrofit dynamic fields alongside normal fields in single json object

In my android app, I am using retrofit to call the API and cast the response json to My Class. I am okay with simple responses but one of them contain dynamic fields (which need to be gathered in a list or map). A sample of result json is something like this:

{
  "_id":"id",
  "name":"somename",
  "paths":[
             {
               "_id":"path id 1",
               "path":"path 1"
             },
             {
               "_id":"path id 2",
               "path":"path 2"
             }
            ],
  "dynamic_field1":"dynamic_value1",
  "dynamic_field2":"dynamic_value2",
  "dynamic_field3":"dynamic_value3"
}

How should I cast this result, in order to have normal fields alongside dynamic fields (In a map or list)?

You can easily cast the dynamic key-value pair with Map

Create the model class like this:

class Response {

   private String id;
   ..

   private final Map<String, String> dynamicValues = new HashMap<>();
   public void addDynamicValues(String key, String value) {
          dynamicValues.put(key, value).
   }
   ....\\ getter setter for methods
}

In your case, I would suggest just get the response in Map and then loop and get known/unknown keys value. There is another way you can create your own JsonMapper to map accordingly. But that much effort would not be useful if this is just for a single API.

 @GET("getResponse/")
 Call<Map<String, Object>> getResponse();

Now execute with Retrofit

 if(response.isSuccessful()) {
            Response apiResponse = new Response();
            Map<String, Object> responseBody = response.body();
            for (Map.Entry<String, Object> entry : responseBody.entrySet()) { 
               System.out.println("Key = " + entry.getKey() + 
                             ", Value = " + entry.getValue());
               if(entry.getKey().equals("_id")) {
                   apiResponse.setId((String) responseBody.get("_id");
               } else if (entry.getKey().equals("name")) {
                   apiResponse.setName((String) responseBody.get("name");
               } else if (entry.getKey().equals("name")){
                  apiResponse.setPaths(responseBody.get("paths");
               } else {
                 apiResponse.addDynamicValues(entry.getKey(), entry.getValue()); 
              }     
          }  
        } else {
            System.out.println(response.errorBody());
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM