java - 使用java解析json

标签 java json

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


            }]

            }
      }]

}

我如何解析上面的 JSON 对象,以便获得信息项和过敏项......

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

}

最佳答案

这是有效的 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'
}

...

希望这有帮助!

关于java - 使用java解析json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15993812/

相关文章:

javascript - 来自 JSON 的最大值

json - 将包含引号的 JSON 插入到 PostgreSQL 中

像自动更正这样的代码需要 Java 帮助

java - 具有简历功能的 PHP 上传文件

java - Android 设置 Accessibility Focus 监听器

java - VMware vCenter Web 客户端 UI 和数据服务调整

java - GSON 需要 BEGIN_ARRAY 但实际是 BEGIN_OBJECT

java - 一些 HWPF POI 文档构建示例

javascript - html - 如何在加载时填充输入文本?

python - Azure服务总线python客户端问题