json字符串解析JSONObject、JSONArray

本文介绍了如何在Java中将JSON字符串转换为JSONObject和JSONArray。通过JSONObject.fromObject()和JSONArray.fromObject()方法,可以实现JSON到Java对象的转换。同时,展示了如何解析包含JSONObject和JSONArray的混合数据,并提供了遍历和获取数据的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

JSONObject:必须是 “{ ”开头  /    JSONArray:必须是 “[ ”开头

以{}开头使用JSONObject.fromObject(“json数据”),将json数据转为java对象、

以[ ]开头使用JSONArray.fromObject(“json数据”),将json数据转为java数组

1 、String str = "{\"id\":\"1234\",\"name\":\"xiaoming\",\"sex\":\"boy\"}";

json字符串转JSONObject  a: JSONObject  jsonObject   =   new JSONObject(str); 

                                            b:JSONObject  jsonObject    =   JSONObject.fromObject(str);

                                            c:JSONObject  jsonObject  =    JSON.parseObject(str);

d:ClassM json = JSON.parseObject(str, ClassM.class);

                                            e:  ClassM   json  =(ClassM)JSONObject.toBean(jsonObject,ClassM.class) 

2、String str = "[{\"id\":\"1234\",\"name\":\"xiaoming\",\"sex\":\"boy\"}]";

                                            a: JSONArray  json   =   new JSONArray(str); 

                                            b:JSONArray  json    =   JSONArray.fromObject(str);         

3、混合解析

String str="{\"start\":   
 [
                  {\"id\":\"1234\",\"data\":[1,2,3],\"count\":[4,5,6]
                  },
                  {\"id\":\"1234\",\"data\":[1,2,3],\"count\":[4,5,6]
                  }

]

}";

JSONObject  jsonObject    =   JSONObject.fromObject(str);

JSONArray jsonArray =jsonObject.getJSONArray("start");

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

     JSONObject  value  = jsonArray.getJSONObject(i);

      String  id =value.getString("id");

    JSONArray jsonData =value.getJSONArray("data");

   JSONArray jsonCout=value.getJSONArray("count");

  for(int j=0;j<jsonData.length(); j++){

           String  jsondata = jsonData.getString(i);

  }

 同理遍历  jsonCout

 }

小结:

JSONObject ------jsonArray     

   JSONObject  jsonObject    =   JSONObject.fromObject(str); 

   JSONArray  json    =   jsonObject.fromObject("arrayName");        混合三    

jsonArray获取jsonObject

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

  JSONObject  value  = jsonArray.getJsonArray(i);

}                      

待补充~


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值