JSONObject与JSONArray总结及部分使用

**

例如

**:在这里插入图片描述
取出name4值过程步骤:1,将以上字符串转换为JSONArray对象;2,取出对象的第一项,JSONObject对象;3,取出name1的值JSONObject对象;4,取出name2的值JSONObject对象;5,取出name4的值value2。

JSONArray getJsonArray=JSONArray.fromObject(arrayStr);//将结果转换成JSONArray对象的形式
JSONObject getJsonObj = getJsonArray.getJSONObject(0);//获取json数组中的第一项
String result=getJsonObj.getJSONObject("name1").getJSONObject("name2").getJSONObject("name4");

————————————————
原网址(总结借鉴一部分):https://blog.csdn.net/lishuangzhe7047/article/details/28880009

Json对象中添加的是键值对,JSONArray中添加的是Json对象

JSONObject Json = new JSONObject();
JSONArray JsonArray = new JSONArray();
 
Json.put("key", "value");//JSONObject对象中添加键值对
JsonArray.add(Json);//将JSONObject对象添加到Json数组中

JSONObject与Map
Map map和json都是键值对,不同的是map中键值对中间用等号分开,json中键值对中间用冒号分开。其实json就是一种特殊形式的map

Map<String,String> strmap=new JSONObject();

Json,String,Map之间的转换

原网址(https://www.cnblogs.com/fgm119/p/3907085.html)

前提是String的格式是map或json类型的
String 转Json

 JSONObject  jasonObject = JSONObject.fromObject(str);

String 转Map

JSONObject  jasonObject = JSONObject.fromObject(str);
Map map = (Map)jasonObject;

在网页之间传递数据出现中文乱码解决方案:

例如请求接口返回一个map或json数据,包含中文

1,先将map或json转成string格式,如果是map类型的,先转成:
json JSONObject json=new JSONObject(map);

json.toJSONString();转成string格式
2,利用URLEncoder.encoder(str,“UTF-8”)或"GBK"对string加密处理,发送加密后的str

3,在接受端,收到str后,URLDecoder.decoder(str,“UTF-8”)解密成正常str,一般要转成json需要去掉开始结尾的引号,str=str.substring(1,str.length()-1),再用JSONObject.formObject(str)将str转成json;之后需要转map,Map map = (Map)json即可

===========================================
// 判读输出对象的类型

boolean isArray = jsonObject.isArray();
boolean isEmpty = jsonObject.isEmpty();
boolean isNullObject = jsonObject.isNullObject();
System.out.println("是否为数组:" + isArray + ", 是否为空:" + isEmpty + ", isNullObject:" + isNullObject);

// 添加属性,在jsonObject后面追加元素。

JsonElement的简单说明
https://blog.csdn.net/chunqiuwei/article/details/49160321

 jsonObject.element("address", "福建省厦门市");
    System.out.println("添加属性后的对象:" + jsonObject);
    System.out.println("-------------------------------------------------");
    // 返回一个JSONArray对象
    JSONArray jsonArray = new JSONArray();
    jsonArray.add(0, "this is a jsonArray value");
    jsonArray.add(1, "another jsonArray value");
    jsonObject.element("jsonArray", jsonArray);
    //在jsonObject后面住家一个jsonArray
    JSONArray array = jsonObject.getJSONArray("jsonArray");
    System.out.println("jsonObject:   "+jsonObject);
    System.out.println("返回一个JSONArray对象:" + array);

具体如何使用可以参考:https://www.cnblogs.com/xiaoliu66007/p/4610829.html

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值