`
shilianjun
  • 浏览: 33858 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

java 解析 生成 json

    博客分类:
  • java
阅读更多
1.
String receiveStr = "{'opType':'add','infostr':[{'infoId':'123456'},{'infoId':'000000'}]}";
JSONObject jsonObject = new JSONObject(recevieStr);
opType = jsonObject.getString("opType");
JSONArray array = jsonObject.getJSONArray("infostr");
for (int i = 0; i < array.length(); i++) {
        JSONObject jsonInfObject = new JSONObject(array.get(i).toString());
        infoId = jsonInfObject.getString("infoId");
}

2.
JSONObject jsonObject = new JSONObject(jsonStr);

//String nameValue = jsonObject.getString("name");
//System.out.println("nameValue is:" + nameValue);

JSONArray jsonArray = jsonObject.names();//变量名

Iterator it = jsonObject.keys();//对应值

for (int i = 0; i < jsonArray.length(); i++) {

        System.out.println(jsonArray.getString(i) + " : " + jsonObject.get((String)it.next()));

}

3.
JSONObject jsonObj;
String jsonStr = "";

//生成JSON格式的字符串
try {
        jsonObj = new JSONObject("{}");

        jsonObj.put("name", "Jordan");

        String[] likes = new String[] { "Basketball", "Baseball", "Racing" };
        jsonObj.put("likes", likes);

        Map<String, String> info = new HashMap<String, String>();
        info.put("weight", "100kg");
        info.put("height", "1.98m");
        info.put("wingspan", "2m");
        jsonObj.put("info", info);

        jsonStr = jsonObj.toString();
        System.out.println(jsonStr);

} catch (JSONException e) {
        e.printStackTrace();
}

//解析JSON格式的字符串
try {

        JSONObject jsonObject = new JSONObject(jsonStr);

        JSONArray jsonArray = jsonObject.names();

        Iterator<?> it = jsonObject.keys();

        for (int i = 0; i < jsonArray.length(); i++) {

                if(jsonArray.getString(i).equals("info")){

                //String childStr = jsonObject.getString("info");
                // it.next();

                String childStr = jsonObject.get((String)it.next()).toString();
                JSONObject jsonObjectChild = new JSONObject(childStr);
                JSONArray jsonArrayChild = jsonObjectChild.names();
                Iterator<?> itChild = jsonObjectChild.keys();
                for (int j = 0; j < jsonArrayChild.length(); j++) {
                        System.out.println("info_" + jsonArrayChild.getString(j) + " : " + jsonObjectChild.get((String)itChild.next()));
                }
                }else{
                        System.out.println(jsonArray.getString(i) + " : " + jsonObject.get((String)it.next()));
                }
        }

} catch (JSONException e) {
        e.printStackTrace();
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics