繁体   English   中英

使用java解析json

[英]parsing json using java

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


            }]

            }
      }]

}

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

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'
}

...

希望这可以帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM