一文教你json字符串与JavaBean对象如何相互转换

工作中经常会遇到在复杂的业务场景中,将数据持久化时某个字段存储的是json字符串,取出数据进行操作时,不能直接对json字符串进行操作,能操作的是JavaBean对象。
或者调用其他的服务(Java应用服务、python服务等),接收到的结果为json字符串,在对结果进行处理时,不能直接操作,需要将其转化为JavaBean对象。

所以,在这些情况下,就需要将json字符串、json对象与JavaBean对象进行转化,来实现需要的操作。
实现方式如下:


pom文件中导入依赖:

        <!-- JSON转换工具类依赖 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.15</version>
        </dependency>
        


1、将json字符串转化为List<JavaBean>对象

数据存储格式为:
在这里插入图片描述
取出的值为:

String resultJson=item.getAnnotationResult();
[{
    
    "attribute":["条件_"],"name":"已注明","property":{
    
    "end_index":2,"start_index":0},"type":101,"value":"已画出"},{
    
    "attribute":["条件_"],"name":"底筋","property":{
    
    "end_index":6,"start_index":4},"type":101,"value":"底钢筋"},{
    
    "attribute":["条件_"],"name":"底筋","property":{
    
    "end_index":16,"start_index":12},"type":101,"value":"底实配钢筋"},{
    
    "attribute":["条件_"],"name":"未绘制","property":{
    
    "end_index":20,"start_index":18},"type":101,"value":"未画出"},{
    
    "attribute":["条件_"],"name":"底筋","property":{
    
    "end_index":25,"start_index":23},"type":101,"value":"底钢筋"},{
    
    "attribute":["条件_"],"name":"双向","property":{
    
    "end_index":27,"start_index":26},"type":101,"value":"双向"},{
    
    "attribute":["条件_"],"name":"厚度值","property":{
    
    "end_index":43,"start_index":39},"type":101,"value":"100mm"}]

将取出的值json串转化为需要的List<JavaBean>对象:

//JSONObject 导入的包为import com.alibaba.fastjson.JSONObject;
List<LabelsDTO> samples= JSONObject.parseArray(resultJson,LabelsDTO.class);

需要的JavaBean对象为:

@Data
public class LabelsDTO {
    
    
    private String name;
    private String value;
    private Integer type;
    private String id;
    private List<String> attribute;
    private PropertyDTO property;
    private String color;
 }


2、将json字符串转化为JavaBean对象

   String result;
   result = ...
   JSONObject jsonObject=JSON.parseObject(result);
   ResultAutoDTO resultAutoDTO = jsonObject.toJavaObject(ResultAutoDTO.class);

需要转化为的JavaBean对象为:

@Data
public class ResultAutoDTO {
    
    
    private int code;
    private String id;
    private String message;
    private DataDTO data;
}


3、将List<JavaBean>对象转化为json字符串

//LabelsDTO见1
List<LabelsDTO> labels=item.getLabels();
String s=JSON.toJSONString(labels);

猜你喜欢

转载自blog.csdn.net/LZ15932161597/article/details/112440699