简体   繁体   中英

GSON how to parse array with dynamic type

Looking at this Json file, KEY is always a String, but VALUE sometimes is a String but sometimes is an typed object with two String fields.

How can I parse it using GSON?

{
    "property": [
        {
            "key": "key_A",
            "value": "value_A"
        },
        {
            "key": "key_B",
            "value": "value_B"
        },
        {
            "key": "key_C",
            "value": {
                "param_C_1": "value_C_1", 
                "param_C_2": "value_C_2"

            }
        }
    ]
}

The first thing is parsing this json file to java that can be done this way :-

 try {
                InputStream is;
                //read the whole json file stored in assets
//below is android way of opening file from local resource folder, you can use other means to open
                is = getApplicationContext().getAssets().open("jsonfile.json");
                int size = is.available();

                byte[] buffer = new byte[size];

                is.read(buffer);

                is.close();

                //convert the json file to string
                String bufferString = new String(buffer);

                JSONObject jsonObject;
                JSONArray jsonArray;
                jsonObject = new JSONObject(bufferString);
                jsonArray=jsonObject.getJSONArray("property");
                for (int i=0;i<jsonArray.length();i++){
                    jsonObject = jsonArray.getJSONObject(i);
                    JSONObject s = jsonArray.optJSONObject(i);
                    String s2 = s.getString("value");
                    if(s2.contains("{")){
                        JSONObject jobject = new JSONObject(s2);
                        String valueUnderValue1 = jobject.getString("param_C_1");
                        String valueUnderValue2 = jobject.getString("param_C_2");
                    }
                }


            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                        } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();


            }

Then make a class which will have all the values you got from the json file. Say that class is MyClass, containing all of the values you got from json file.

make MyClass object and then

MyClass obj = new MyClass();
Gson gson = new Gson();
JSONObject onj = new JSONObject();
        JSONArray userDataValues = new JSONArray();
//again convert to json
userDataValues.put(new JSONObject(gson.toJson(obj)));
//serialized the object
onj.put("property", userDataValues);

I hope this is what you want.

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