最近,工作中会涉及到Java对象与JSON字符串相互转换,虽然说并不难,但打算还是梳理一番,主要内容有:
开始之前,需要在 pom.xml 引入相关的 jar 包:
org.projectlombok
lombok
1.16.10
provided
com.alibaba
fastjson
1.2.75
接着,创建一个普通对象,使用 lombok 提供的注解:
@Data
public class ExtInfo {
private String orderId;
private String creatTime;
private String postion;
private String orderType;
private String amount;
}
测试1:json字符串 与 普通对象 互转
public class Demo {
@Test
void test1() {
// json字符串转普通对象
String jsonStr = "{\"orderId\":\"1111\",\"creatTime\":\"20210817223001\",\"postion\":\"hangZhou xiXi\",\"orderType\":\"4\",\"amount\":\"20\"}";
JSONObject jsonObject = JSONObject.parseObject(jsonStr);
ExtInfo extInfo = JSONObject.toJavaObject(jsonObject, ExtInfo.class);
System.out.println(extInfo);
System.out.println(extInfo.getOrderId());
// 普通对象转json字符串
String str = JSONObject.toJSONString(extInfo);
System.out.println(str);
}
}
测试结果:
ExtInfo(orderId=1111, creatTime=20210817223001, postion=hangZhou xiXi, orderType=4, amount=20)
1111
{"amount":"20","creatTime":"20210817223001","orderId":"1111","orderType":"4","postion":"hangZhou xiXi"}
测试2:json字符串数组 与 List集合对象 互转
public class Demo2 {
@Test
void test2() {
// json字符串数组转对象List集合
String jsonStrArray = "[{\"orderId\":\"1111\",\"creatTime\":\"20210817223001\",\"postion\":\"hangZhou xiXi\",\"orderType\":\"4\",\"amount\":\"20\"}]";
JSONArray jsonArray = JSONObject.parseArray(jsonStrArray);
// 方式一、根据索引获取 JSONArray 中的对象
ExtInfo extInfo1 = jsonArray.getObject(0, ExtInfo.class);
System.out.println(extInfo1);
// 方式二、转成List,再从List获取对象
List extInfos = jsonArray.toJavaList(ExtInfo.class);
ExtInfo extInfo2 = extInfos.get(0);
System.out.println(extInfo2);
// List集合对象转json字符串数组
String strs = JSONObject.toJSONString(extInfos);
System.out.println(strs);
}
}
测试结果:
ExtInfo(orderId=1111, creatTime=20210817223001, postion=hangZhou xiXi, orderType=4, amount=20)
ExtInfo(orderId=1111, creatTime=20210817223001, postion=hangZhou xiXi, orderType=4, amount=20)
[{"amount":"20","creatTime":"20210817223001","orderId":"1111","orderType":"4","postion":"hangZhou xiXi"}]
测试3:json字符串 与 装有对象的Map 互转
public class Demo3 {
@Test
void test3() {
// map格式转对象
String mapJsonStr = "{\"level\":{\"orderId\":\"1111\",\"creatTime\":\"20210817223001\",\"postion\":\"hangZhou xiXi\",\"orderType\":\"4\",\"amount\":\"20\"}}";
Map extInfoMap = JSONObject.parseObject(
mapJsonStr,
new TypeReference>() {});
System.out.println(extInfoMap);
System.out.println(extInfoMap.get("level"));
// 对象转map格式
String mapStr = JSONObject.toJSONString(extInfoMap);
System.out.println(mapStr);
}
}
测试结果:
{level=ExtInfo(orderId=1111, creatTime=20210817223001, postion=hangZhou xiXi, orderType=4, amount=20)}
ExtInfo(orderId=1111, creatTime=20210817223001, postion=hangZhou xiXi, orderType=4, amount=20)
{"level":{"amount":"20","creatTime":"20210817223001","orderId":"1111","orderType":"4","postion":"hangZhou xiXi"}}