java提取object到字符串_【Java】JSONObject、String、JSONArray之间的相互转换

本文介绍了如何在Java中将String转换为JSONObject,再从JSONObject获取数据,以及String与JSONArray之间的转换。提供了详细的示例代码,展示了如何解析JSON字符串,获取数组数据,并将数据打印出来。

String 类型转 JSONObject

JSONObject jsonObject = JSONObject.parseObject(json);

JSONObject获取数据

// 得到数组String

String items = jsonObject.getString("items");

String类型转JSONArray

JSONArray jsonArray = JSONArray.parseArray(items);

注意:格式必须是JSONArray类型

JSONArry转String

String s = JSONArray.toJSONString(jsonArray);

JSONArray返回前端数据

// 直接返回数组格式,不要返回string,会有转义字符

if (object != null ){

JSONArray commentPicturesLink = object.getJSONArray("commentPicturesLink");

object.put("commentPicturesLink",commentPicturesLink);

}

示例:

String json = "{\n" +

"\"placePhoneNo\":\"15982229730\",\n" +

"\"placeName\":\"zbb\",\n" +

"\"receivingPhoneNo\":\"15302289730\",\n" +

"\"receivingName\":\"zbbbb\",\n" +

"\"receivingAddress\":\"成都市青羊区\",\n" +

"\"receivingTime\":\"2020-01-21 15:10:20\",\n" +

"\"items\":[\n" +

"{\"itemName\":\"华为p40\",\"itemNum\":3,\"itemPrice\":23.23,\"itemPicture\":\"https://cdn.huawei.net/Storage/Shop/1/GoodsPropertyValues/10431927108622508.jpg\"},\n" +

"{\"itemName\":\"小米32\",\"itemNum\":13,\"itemPrice\":500.23,\"itemPicture\":\"https://cdn.huawei.net/Storage/Shop/1/GoodsPropertyValues/10431927108622508.jpg\"}\n" +

"]\n" +

"}";

// String 转JSONObject

JSONObject jsonObject = JSONObject.parseObject(json);

// 得到数组String

String items = jsonObject.getString("items");

// String 转 JSONArray

JSONArray jsonArray = JSONArray.parseArray(items);

// 获取数组数据

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

String jsonArrayString = jsonArray.get(i).toString();

JSONObject object = JSONObject.parseObject(jsonArrayString);

System.out.println("itemName = " + object.getString("itemName"));

System.out.println("itemNum = " + object.getString("itemNum"));

System.out.println("itemPrice = " + object.getString("itemPrice"));

System.out.println("itemPicture = " + object.getString("itemPicture"));

System.out.println("--------------------------------------------------------------------------");

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值