java 解析 生成 json

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();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值