简体   繁体   中英

Parse json containing dynamic fields using Gson

I have a model like this:

class MyModel{
    String id;
    String name;
    String field;

   //Getters and setters
}

I am parsing the json using Gson using the below code

// Returns the json containing list of objects
// with properties supplied to the method
String response = getResponse(new String[] { "id", "name", "value",
  {A variable field whose value is determined at runtime}});
MyModel obj = new Gson().fromJson(response,
    new TypeToken<List<MyModel>>() {}.getType());

The code works fine with 3 pre-defined fields. There is a fourth field whose name is a variable (determined at runtime), I cannot create a hardcoded field in the model as the field is not fixed. How can I parse such a json where one field is dynamic?

You could try these options:

  • Gson 2.5 supports multiple field names for the same variable. If the value is determined in runtime but the set of values is limited then you could do something like this:

     @SerializedName(value="name1", alternate={"name2", "name3"}) String b; 
  • Create a custom deserializer:

     public static class YourModelDeserializer implements JsonDeserializer<YourModel> { @Override public YourModel deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { /* Deserialize here */; } } 

You can get all key names by below code:

JSONObject jsonObject = new JSONObject(response);
Iterator keys = jsonObject.keys();

 while(keys.hasNext()) {
       String dynamicKey = (String)keys.next();
       JSONObject currentDynamicValue = jsonObject.getJSONObject(dynamicKey);
  }

You can use ArrayList or Array to save all key names.

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