GSON如何用动态类型解析数组

时间:2012-11-13 16:11:36

标签: java json parsing types gson

查看此Json文件,KEY始终是String,但VALUE有时是String,但有时是带有两个String字段的类型化对象。

如何使用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"

            }
        }
    ]
}

1 个答案:

答案 0 :(得分:0)

第一件事是将这个json文件解析为java,可以完成  这样: -

 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();


            }

然后创建一个具有json文件中所有值的类。 假设该类是MyClass,包含从json文件获得的所有值。

制作MyClass对象,然后

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);

我希望这就是你想要的。

相关问题