背景:
发现A类返回的json可以映射到B类里面,然后就进行测试
XX类
import lombok.Data; @Data public class xx { private String a; private String b; public xx(){}; public xx(String a ,String b){ this.a=a; this.b=b; }; }
Tub类
package com.example.number; import lombok.Data; @Data public class Tub { private String a; private String b; public Tub(){}; public Tub(String a , String b){ this.a=a; this.b=b; };
test 测试文件
import com.alibaba.fastjson.JSONObject;
public static void main(String[]args){ Tub Tub =new Tub("张三","李四"); System.out.println(Tub); // java类转json字符串 String Tubjson=JSONArray.toJSONString(Tub); System.out.println(Tubjson); // json字符串转java类 xx xx = JSONObject.parseObject(Tubjson,xx.class); System.out.println(xx); }
终端输出
Tub(a=张三, b=李四)
{"a":"张三","b":"李四"}
xx(ab=null, b=李四)
主要这2句
java类转json字符串
String Tubjson= JSONObject.toJSONString(Tub);
json字符串转java类
xx xx = JSONObject.parseObject(Tubjson,xx.class);
maven依赖
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.59</version> </dependency>
参考: https://blog.csdn.net/kswkly/article/details/106984153?utm_term=fastjson%E5%AD%97%E7%AC%A6%E4%B8%B2%E8%BD%AC%E6%88%90%E5%AF%B9%E8%B1%A1&utm_medium=distribute.pc_aggpage_search_result.none-task-blog-2~all~sobaiduweb~default-0-106984153&spm=3001.4430