Parsing JSON response using GSON with dynamic Key

亡梦爱人 提交于 2019-12-23 03:42:11

问题


This is how my JSON looks like and I have to parse the JSON, how can this be done using GSON

{
  "data": {
    "a": {
      "abc": {
        "c": "d"
      }
    }
  }
}

In which "a" is dynamic key which may vary from time to time. I am unable to find a solution right now


回答1:


Model

public class Model {

    private HashMap<String, String> data;

    public Model() {
    }
}

Convert json string to Hashmap using Gson & prepare data from hashmap

Gson gson = new Gson();
Type typeHashMap = new TypeToken<Map<String, String>>(){}.getType();
Map<String,String> map = gson.fromJson(YOUR_JSON, typeHashMap);

Set<Map.Entry<String, String>> entrySet = data.entrySet();

    Iterator iterator = entrySet.iterator ();

    for(int j = 0; j < entrySet.size(); j++) {
        try {
            Map.Entry entry = (Map.Entry) iterator.next();
            String key = entry.getKey().toString();
            String value = entry.getValue().toString();
            //Add it to your list
        }
        catch(NoSuchElementException e) {
            e.printStackTrace();
        }
        break;
    }



回答2:


I am not sure if internal part abc is known to you or not. If it is known to you then you can surely do it with GSON. You have to create the class for the inner known object as below:

public class ABC {
public C abc;}

Then create the Class for C:

public class C {
public String c;}

Then just pass the ABC class as the hashmap value as below:

public HashMap<String, ABC> a;


来源:https://stackoverflow.com/questions/43224188/parsing-json-response-using-gson-with-dynamic-key

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!