2012-11-13 13 views
2

查看這個Json文件,KEY始終是一個字符串,但VALUE有時是一個字符串,但有時是一個帶有兩個字符串字段的類型化對象。GSON如何用動態類型解析數組

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

      } 
     } 
    ] 
} 

回答

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

我希望這是你想要的。