1

I have this response json, which the keys are dynamic, sometimes I have only 3 items in "result" and sometime I have 5 or more. How do I have to write the class to deserialize it correctly? The key and value can be dynamic in name and number. i thought i just need a list?

Main Class

 public static void main(String[] args) {

    String response = "{\n" +
            "    \"error\": [],\n" +
            "    \"result\": {\n" +
            "        \"value11\": \"0.0233260\",\n" +
            "        \"value22\": \"59.2500\",\n" +
            "        \"value33\": \"0.0233260300\",\n" +
            "        \"value44\": \"0.00000000\"\n" +
            "    }\n" +
            "}";

    Gson gson = new Gson();
    var responseBalance= gson.fromJson(response, ResponseIds.class);
    System.out.println("Print " + responseBalance.getResult().getData());
}

ResponseIds Class

 public class ResponseIds {

 @SerializedName("result")
 private Result result;

 @SerializedName("error")
 private List<Object> error;

 public Result getResult(){
     return result;
 }

 public List<Object> getError(){
     return error;
 }
}

Result Class

public class Result{

private  HashMap<String, String> data;;

public HashMap<String, String> getData() {
    return data;
}

public void setData(HashMap<String, String> data) {
    this.data = data;
}
}

Edit: Ok this is a simple solution. Result itself is a map

public class ResponseIds {

@SerializedName("result")
private Map<String, String> result;

@SerializedName("error")
private List<Object> error;

public Map<String, String> getResult() {
    return result;
}

}
User1751
  • 150
  • 2
  • 10
  • Can you use Jackson? Jackson has the `@JsonAnySetter` feature – Paul Samsotha Nov 06 '22 at 21:13
  • You're using the correct approach. To handle dynamic key/values, you need Map structure. Did you face any issues with provided code? Similar question: https://stackoverflow.com/questions/6796662/using-gson-to-parse-a-json-with-dynamic-key-and-value-in-android – Vadim Beskrovnov Nov 06 '22 at 21:28
  • @PaulSamsotha No unfortunately not, we only use gson – User1751 Nov 06 '22 at 23:26
  • @VadimBeskrovnov Thank you, I already see this answer but I don't understand the approach with the TypeToken. Do I need to use this in the Result class or in the ResponseId Class? With the current approach I get null – User1751 Nov 06 '22 at 23:26
  • 2
    `result` should just be a `Map` itself. – Sotirios Delimanolis Nov 06 '22 at 23:48

0 Answers0