引入 fastjosn 包实现互转:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.41</version>
</dependency>
互转实例:
package com.example.demo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.List;
import java.util.Map;
public class JsonTransTest {
public static void main(String[] args) {
String jsonObjString = "{\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" +
"}";
// jsonObjString 转 JSONObject
JSONObject jsonObject = JSONObject.parseObject(jsonObjString);
// jsonObjString 转 Map
Map map = JSONObject.parseObject(jsonObjString, Map.class);
// 得到数组String
String items = jsonObject.getString("items");
// String 转 JSONArray
JSONArray jsonArray = JSONArray.parseArray(items);
//从jsonObject直接获取jsonArray
JSONArray jsonArray2 = jsonObject.getJSONArray("items");
//JSONArray 转 String
String jsonArrayString = JSONArray.toJSONString(jsonArray);
//或者
String jsonArrayString2 = jsonArray.toJSONString();
// jsonArrayString 转 List
List list = JSONObject.parseObject(jsonArrayString, List.class);
// 或者
List list2 = JSONArray.parseObject(jsonArrayString, List.class);
// jsonArrayString 转 List<Map>: 方式一
List<Map<String, Object>> listmap = JSONArray.parseObject(jsonArrayString, List.class);
// jsonArrayString 转 List<Map>: 方式二
List<Map<String, Object>> listmap2 = (List<Map<String, Object>>)JSONArray.parse(jsonArrayString);
//List 转 JSONArray: 先转jsonString, 再转JSONArray
JSONArray jsonArray3 = JSONArray.parseArray(JSON.toJSONString(list));
// Map 转 JSONObject: 先转jsonString, 再转JSONObject
JSONObject jsonObject2 = JSONObject.parseObject(JSON.toJSONString(map));
}
}