01.概述
如果我们接收到的是一个json字符串,我们该如何对该字符串进行解析?
- 方式一:使用实体类进行解析
- 方式二:使用map进行解析
使用的依赖jar包:fastjson
compile('com.alibaba:fastjson:1.2.xx')
02.对json字符串进行解析
使用实体类进行解析
创建一个用于接收的实体类:使用json字符串中的那些字段,实体类的属性值一定要和JSON串中的key
对应
假设JSON字符串如下:
"{\"bornTime\":\"2022-09-30 19:48:59\",\"userName\":\"AISMALL\",\"sex\":\"man\",\"age\":18}"
对应的实体类属性就应该定义成如下的样子:
public class PersonInfoDto {
private Date bornTime;
private String userName;
private String sex;
private Integer age;
public Date getBornTime() {
return bornTime;
}
public void setBornTime(Date bornTime) {
this.bornTime = bornTime;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "PersonInfoDto{" +
"bornTime=" + bornTime +
", userName='" + userName + '\'' +
", sex='" + sex + '\'' +
", age=" + age +
'}';
}
}
代码示例:
public class test01 {
public static void main(String[] args) {
String jsonStr = "{\"bornTime\":\"2022-09-30 19:48:59\",\"userName\":\"AISMALL\",\"sex\":\"man\",\"age\":18}";
PersonInfoDto personInfoDto = JSONObject.parseObject(jsonStr, PersonInfoDto.class);
System.out.println(personInfoDto.toString());
}
}
运行结果:
PersonInfoDto{bornTime=Fri Sep 30 19:48:59 CST 2022, userName='AISMALL', sex='man', age=18}
使用实体类解析拓展
public class test01 {
public static void main(String[] args) {
// json串里面的key与实体类字段匹配几个就会赋值几个,匹配不上的赋值为null
String jsonStr1 ="{\"bornTime\":\"2022-09-30 19:48:59\"}";
PersonInfoDto personInfoDto1 = JSONObject.parseObject(jsonStr1, PersonInfoDto.class);
System.out.println("personInfoDto1: " + personInfoDto1);
// json串中出现重复的字段,就会使用后者进行覆盖
String jsonStr2 ="{\"bornTime\":\"2022-09-30 19:48:59\",\"userName\":\"AISMALL\",\"userName\":\"AISMALL2\"}";
PersonInfoDto personInfoDto2 = JSONObject.parseObject(jsonStr2, PersonInfoDto.class);
System.out.println("personInfoDto2: " + personInfoDto2);
// json串里面的key与实体类字段匹配几个就会赋值几个,不管该传有多长,只取匹配到的key的value给实体类赋值
String jsonStr3 ="{\"bornTime\":\"2022-09-30 19:48:59\",\"userName\":\"AISMALL\",\"sex\":\"man\",\"age\":18,\"age2\":18}";
PersonInfoDto personInfoDto3 = JSONObject.parseObject(jsonStr3,PersonInfoDto.class);
System.out.println("personInfoDto3: " + personInfoDto3);
// 刚好对应的情况
String jsonStr4="{\"bornTime\":\"2022-09-30 19:48:59\",\"userName\":\"AISMALL\",\"sex\":\"man\",\"age\":18}";
PersonInfoDto personInfoDto4 = JSONObject.parseObject(jsonStr4, PersonInfoDto.class);
System.out.println("personInfoDto4: " + personInfoDto4);
}
}
运行结果:
personInfoDto1: PersonInfoDto{bornTime=Fri Sep 30 19:48:59 CST 2022, userName='null', sex='null', age=null}
personInfoDto2: PersonInfoDto{bornTime=Fri Sep 30 19:48:59 CST 2022, userName='AISMALL2', sex='null', age=null}
personInfoDto3: PersonInfoDto{bornTime=Fri Sep 30 19:48:59 CST 2022, userName='AISMALL', sex='man', age=18}
personInfoDto4: PersonInfoDto{bornTime=Fri Sep 30 19:48:59 CST 2022, userName='AISMALL', sex='man', age=18}
小结
- json串里面的key与实体类字段匹配几个就会赋值几个,不管该传有多长,只取匹配到的key的value给实体类赋值,匹配不上的赋值为null。
- json串中出现重复的字段,就会使用后者进行覆盖。
使用map进行解析
public class test01 {
public static void main(String[] args) {
// json字符串
String jsonStr = "{\"age\":18,\"sex\":\"man1\",\"userName\":\"AISMALL1\"}";
//====================方式一==============================
Map maps = (Map)JSON.parse(jsonStr);
for (Object map : maps.entrySet()) {
System.out.println(((Map.Entry)map).getKey()+": " + ((Map.Entry)map).getValue());
}
//====================方式二==============================
Map mapTypes =JSON.parseObject(jsonStr);
for(Object obj :mapTypes.keySet()){
System.out.println("key: " + obj + " value: " + mapTypes.get(obj));
}
//====================方式三==============================
Map mapType = JSON.parseObject(jsonStr, Map.class);
System.out.println("这个是用JSON类,指定解析类型,来解析JSON字符串!!!");
for(Object obj :mapType.keySet()){
System.out.println("key: " + obj + " value: " + mapType.get(obj));
}
//====================方式四==============================
Map json =(Map)JSONObject.parse(jsonStr); //用Json对象解析成Map类型
for (Object map : json.entrySet()){
System.out.println(((Map.Entry)map).getKey() + ": "+((Map.Entry)map).getValue());
}
//====================方式五==============================
JSONObject jsonobject = JSONObject.parseObject(jsonStr);
for(Object map:jsonobject.entrySet()){
System.out.println(((Map.Entry)map).getKey()+": "+((Map.Entry)map).getValue());
}
}
}
03.Map和json字符串的互相转换
3.1.json字符串转换为Map
参考:使用map进行解析
3.2.Map转换为json字符串
public class test01 {
public static void main(String[] args) {
// 创建一个Hashmap
Map<String, Object> paraMap = new HashMap();
paraMap.put("userName","AISMALL");
paraMap.put("sex","man");
paraMap.put("age",18);
// 方式一:转换为json字符串
String jsonStr = JSONObject.toJSONString(paraMap);
System.out.println("jsonStr: " + jsonStr);
// 方式二:转换为json字符串
String jsonStr2 = Json.toJson(paraMap);
System.out.println("jsonStr2: " + jsonStr2);
}
}
运行结果:
jsonStr: {"sex":"man","userName":"AISMALL","age":18}
jsonStr2: {"sex":"man","userName":"AISMALL","age":18}
04.json操作的一些小技巧
4.1.json字符转换为实体类
前面已经介绍了:
JSONObject.parseObject(jsonString, PersonInfoDto .class);
4.2.实体类转json字符串
public class test01 {
public static void main(String[] args) {
Date date = new Date(); // 创建一个Date对象,获取当前时间
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 指定格式化格式
f.format(date); // 将当前时间袼式化为指定的格式
PersonInfoDto personInfoDto = new PersonInfoDto();
personInfoDto.setBornTime(date);
personInfoDto.setUserName("AISMALL");
personInfoDto.setSex("man");
personInfoDto.setAge(18);
String jsonStr = JSON.toJSONString(personInfoDto);
System.out.println(jsonStr);
}
}
运行结果:
{"age":18,"bornTime":1665113383685,"sex":"man","userName":"AISMALL"}
4.3.json字符串转换为json对象
public class test01 {
public static void main(String[] args) {
// json字符串
String jsonStr = "{\"test\":\"test\",\"Result\":[{\"Result1\":\"Result1\",\"Detail1\":\"Detail1\"},{\"Result2\":\"Result2\",\"Detail2\":\"Detail2\"},{\"Result3\":\"Result3\",\"Detail3\":\"Detail3\"}]}";
// json字符串转换为jsonObject
JSONObject jSONObject = JSONObject.parseObject(jsonStr);
System.out.println(jSONObject);
// 根据Key取出Json对象中的值
String testStr = jSONObject.getString("test");
System.out.println("testStr: " + testStr);
}
}
运行结果:
{"test":"test","Result":[{"Detail1":"Detail1","Result1":"Result1"},{"Detail2":"Detail2","Result2":"Result2"},{"Detail3":"Detail3","Result3":"Result3"}]}
testStr: test
注意:
- Json对象和Json字符串的区别在于,
Json对象(JSONObject)
里面有很多定义好的方法可以帮助我们根据Key取出Json对象中的值,后面我们也会演示几个JSONObject提供的方法。
4.4.json对象转换为json字符串
public class test01 {
public static void main(String[] args) {
// json字符串
String jsonStr = "{\"test\":\"test\",\"Result\":[{\"Detail1\":\"Detail1\",\"Result1\":\"Result1\"},{\"Detail2\":\"Detail2\",\"Result2\":\"Result2\"},{\"Detail3\":\"Detail3\",\"Result3\":\"Result3\"}]}";
// json字符串转换为jsonObject
JSONObject jSONObject = JSONObject.parseObject(jsonStr);
// json对象转换为json字符串
String jsonObjectConv = JSON.toJSONString(jSONObject);
System.out.println(jsonObjectConv);
}
}
运行结果:
{"test":"test","Result":[{"Detail1":"Detail1","Result1":"Result1"},{"Detail2":"Detail2","Result2":"Result2"},{"Detail3":"Detail3","Result3":"Result3"}]}
4.5.json字符串数组转换json数组
注意:json字符串数组,即String是JSONArray格式的字符串
public class test01 {
public static void main(String[] args) {
// json字符串数组
String jsonArr = "[{\"Detail1\":\"Detail1\",\"Result1\":\"Result1\"},{\"Detail2\":\"Detail2\",\"Result2\":\"Result2\"},{\"Detail3\":\"Detail3\",\"Result3\":\"Result3\"}]";
JSONArray jsonArray= JSONArray.parseArray(jsonArr);
// 转换成Json字符串数组之后,就可以遍历了,字符串是无法遍历的
for (Object jsonStr:jsonArray) {
System.out.println(jsonStr);
}
}
}
运行结果:
{"Detail1":"Detail1","Result1":"Result1"}
{"Detail2":"Detail2","Result2":"Result2"}
{"Detail3":"Detail3","Result3":"Result3"}
4.6.List<实体类>转json数组
public class test01 {
public static void main(String[] args) {
PersonInfoDto personInfoDto1 = new PersonInfoDto();
personInfoDto1.setUserName("AISMALL1");
personInfoDto1.setSex("man1");
personInfoDto1.setAge(18);
PersonInfoDto personInfoDto2 = new PersonInfoDto();
personInfoDto2.setUserName("AISMALL2");
personInfoDto2.setSex("man2");
personInfoDto2.setAge(19);
List<PersonInfoDto> list = new ArrayList<>();
list.add(personInfoDto1);
list.add(personInfoDto2);
// 转换为json字符串
String jsonStr = JSONObject.toJSONString(list);
System.out.println("jsonStr: " + jsonStr);
// json字符串转换为json数组
JSONArray jsonArray= JSONArray.parseArray(jsonStr);
// 转换成Json字符串数组之后,就可以遍历了,字符串是无法遍历的
for (Object jsonStr1:jsonArray) {
System.out.println(jsonStr1);
}
}
}
运行结果:
jsonStr: [{"age":18,"sex":"man1","userName":"AISMALL1"},{"age":19,"sex":"man2","userName":"AISMALL2"}]
{"sex":"man1","userName":"AISMALL1","age":18}
{"sex":"man2","userName":"AISMALL2","age":19}
4.7.json数组转List<实体类>
public class test01 {
public static void main(String[] args) {
// json字符串数组
String jsonStr = "[{\"age\":18,\"sex\":\"man1\",\"userName\":\"AISMALL1\"},{\"age\":19,\"sex\":\"man2\",\"userName\":\"AISMALL2\"}]";
System.out.println("jsonStr: " + jsonStr);
// json字符串转换为json数组
JSONArray jsonArray= JSONArray.parseArray(jsonStr);
List<PersonInfoDto> personInfoDtoList = jsonArray.toJavaList(PersonInfoDto.class);
for (PersonInfoDto personInfoDto:personInfoDtoList) {
System.out.println("personInfoDto: " + personInfoDto);
}
}
}
运行结果:
jsonStr: [{"age":18,"sex":"man1","userName":"AISMALL1"},{"age":19,"sex":"man2","userName":"AISMALL2"}]
personInfoDto: PersonInfoDto{bornTime=null, userName='AISMALL1', sex='man1', age=18}
personInfoDto: PersonInfoDto{bornTime=null, userName='AISMALL2', sex='man2', age=19}
05.josnObject操作的一些小技巧
JSONObject如下:
{
"test": "test",
"Result": [
{
"Result1": "Result1",
"Detail1": "Detail1"
},
{
"Result2": "Result2",
"Detail2": "Detail2"
},
{
"Result3": "Result3",
"Detail3": "Detail3"
}
]
}
5.1.JSONObject中的数组提取为JSONArray
public class test01 {
public static void main(String[] args) {
// json字符串
String jsonStr = "{\"test\":\"test\",\"Result\":[{\"Result1\":\"Result1\",\"Detail1\":\"Detail1\"},{\"Result2\":\"Result2\",\"Detail2\":\"Detail2\"},{\"Result3\":\"Result3\",\"Detail3\":\"Detail3\"}]}";
// json字符串转换为jsonObject
JSONObject jSONObject = JSONObject.parseObject(jsonStr);
// 获取里面的Json字符串数组
JSONArray jsonArray = jSONObject.getJSONArray("Result");
// 转换成Json字符串数组之后,就可以遍历了,字符串是无法遍历的
for (Object jsonStr2:jsonArray) {
System.out.println(jsonStr2);
}
}
}
运行结果
[{"Detail1":"Detail1","Result1":"Result1"},{"Detail2":"Detail2","Result2":"Result2"},{"Detail3":"Detail3","Result3":"Result3"}]
5.2.JSONObject获取value
public class test01 {
public static void main(String[] args) {
// json字符串
String jsonStr = "{\"test\":\"test\",\"Result\":[{\"Result1\":\"Result1\",\"Detail1\":\"Detail1\"},{\"Result2\":\"Result2\",\"Detail2\":\"Detail2\"},{\"Result3\":\"Result3\",\"Detail3\":\"Detail3\"}]}";
// json字符串转换为jsonObject
JSONObject jSONObject = JSONObject.parseObject(jsonStr);
// 返回值为String类型
String testStr = jSONObject.getString("test");
System.out.println("testStr: " + testStr);
// 返回值为Object类型
Object testObject = jSONObject.get("Result");
System.out.println("testObject: " + testObject);
}
}
运行结果:文章来源:https://www.toymoban.com/news/detail-492493.html
testStr: test
testObject: [{"Detail1":"Detail1","Result1":"Result1"},{"Detail2":"Detail2","Result2":"Result2"},{"Detail3":"Detail3","Result3":"Result3"}]
06.总结
更多方法可以去查看JSONArray
,JSONObject
的源码。文章来源地址https://www.toymoban.com/news/detail-492493.html
到了这里,关于将json字符串与实体类互相转换的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!