2013-04-13 116 views
0
{ 
    "Items": [{ 
      "__type": "Section1:#com.test.example", 
      "Info": {    
      }, { 
      "__type": "Section2:#com.test.example2", 
      "Allergy": [{ 


      }] 

      } 
     }] 

} 

我怎么能分析上面的JSON对象,让我得到信息的项目和过敏的物品....解析JSON使用Java

JSONObject documentRoot = new JSONObject(result); 
JSONArray documentChild = documentRoot.getJSONArray("Items"); 
JSONObject child = null; 
for (int i = 0; i < documentChild.length(); i++) { 
    child = documentChild.getJSONObject(i); 

} 
+3

上面粘贴的内容无效JSON。你能直接从有效的JSON源复制/粘贴吗? – mjuarez

+1

请查看[Gson](https://code.google.com/p/google-gson/)这类内容。就像'Gson.fromJson()'一样简单,让对象脱离JSON字符串。无论如何,JSON确实看起来不正常。 – gausss

回答

2

这是有效的JSON:检查有效期在这里:http://jsonlint.com/

{ 
    "Items": [ 
     { 
      "__type": "Section1:#com.test.example", 
      "Info": {} 
     }, 
     { 
      "__type": "Section2:#com.test.example2", 
      "Allergy": [ 
       {} 
      ] 
     } 
    ] 
} 

尝试:

public static final String TYPE_KEY = "__type"; 
public static final String TYPE1_VAUE = "Section1:#com.test.example"; 
public static final String TYPE2_VAUE = "Section2:#com.test.example2"; 


public static final String INFO_KEY = "Info"; 
public static final String ALLERGY_KEY = "Allergy"; 

.... 

String infoString = null; 
JSONArray allergyArray = null; 

for (int i = 0; i < documentChild.length(); i++) { 
    child = documentChild.getJSONObject(i); 

    final String typeValue = child.getString(TYPE_KEY); 

    if(TYPE1.equals(typeValue)) { 
     infoString = child.getString(INFO_KEY); 
    }else if(TYPE2.equals(typeValue)) { 
     allergyArray = child.getJSONArray(ALLERGY_KEY); 
    } 
} 

if(null != infoString) { 
    // access the 'Info' value in 'infoString' 
} 

if(null != allergyArray) { 
    // access the 'Allergy' array in 'allergyArray' 
} 

... 

希望这有助于!