json json数组,json字符串解析

1. 
Java代码   收藏代码
  1. import org.codehaus.jettison.json.JSONArray;  
  2. import org.codehaus.jettison.json.JSONException;  
  3. import org.codehaus.jettison.json.JSONObject;  
  4.   
  5. public class DateJsonValueProcessor {  
  6.     public static void main(String[] args) {  
  7.         try {  
  8.             String result = "{'id':{'a':'0','b':'1'},'users':[{'toid':1,'tosex':2,'realname':'zs'},{'toid':44,'tosex':55,'realname':'zs'}]}";  
  9.   
  10.             JSONObject json = new JSONObject(result);  
  11.             System.out.println("取id值:" + json.get("id"));  
  12.             System.out.println("取id中a值:" + json.getJSONObject("id").get("a"));  
  13.             System.out.println("取id中b值:" + json.getJSONObject("id").get("b"));  
  14.             JSONArray jsonArray = json.getJSONArray("users");  
  15.             int iSize = jsonArray.length();  
  16.             System.out.println("json中数组Size:" + iSize);  
  17.             for (int i = 0; i < iSize; i++) {  
  18.                 JSONObject jsonObj = jsonArray.getJSONObject(i);  
  19.                 System.out.println("[" + i + "]toid=" + jsonObj.get("toid"));  
  20.                 System.out.println("[" + i + "]tosex=" + jsonObj.get("tosex"));  
  21.                 System.out.println();  
  22.             }  
  23.         } catch (JSONException e) {  
  24.             e.printStackTrace();  
  25.         }  
  26.     }  
  27. }  


输出: 
取id值:{"a":"0","b":"1"} 
取id中a值:0 
取id中b值:1 
json中数组Size:2 
[0]toid=1 
[0]tosex=2 

[1]toid=44 
[1]tosex=55 

2. 
Java代码   收藏代码
  1. import org.codehaus.jettison.json.JSONObject;  
  2.   
  3. public class json2 {  
  4.     public static void main(String[] args) throws Exception {  
  5.         String result = "{'error':{'code':'0','info':'错误由未知错误引起'},'loginStr':{'userid':'12345','name':'黑色头发','sex':1,'url':'http://heisetoufa.iteye.com','devtype':1,'loginip':'10.10.10.10'}}";  
  6.   
  7.         JSONObject json = new JSONObject(result);  
  8.         JSONObject error = json.getJSONObject("error");  
  9.         if (error.getInt("code") == 0) {  
  10.             JSONObject user = json.getJSONObject("loginStr");  
  11.             long userId = user.getLong("userid");  
  12.             System.out.println("userID:" + userId);  
  13.             System.out.println("info:" + error.getString("info"));  
  14.             System.out.println("name:" + user.getString("name"));  
  15.         } else {  
  16.         }  
  17.     }  
  18. }  


输出: 
userID:12345 
info:错误由未知错误引起 
name:黑色头发 

黑色头发:http://heisetoufa.iteye.com/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值