Java中Java对象和JSON字符串的相互转化

将java对象转换为Json字符串 或者 将Json字符串转换为Java对象

调试代码:

import com.alibaba.fastjson.JSON;
import java.util.Arrays;

public class TestFastJson {

    public static void main(String[] args) {
        Teacher teacher = new Teacher();
        teacher.setId("T1");
        teacher.setName("李老师");
        teacher.setSubjects(Arrays.asList("数学", "体育"));
        
        // java对象转json字符串 *****************************************************************************************
        String jsonString = JSON.toJSONString(teacher);
        
        // json字符串转java对象 *****************************************************************************************
        Teacher teacherObject = JSON.parseObject(jsonString, Teacher.class);
        
        System.out.println();
    }
    
}

调试结果
Java中Java对象和JSON字符串的相互转化_第1张图片
使用的Teacher.class


import java.util.List;

public class Teacher {
    
    private String id;
    
    private String name;

    private List<String> subjects;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<String> getSubjects() {
        return subjects;
    }

    public void setSubjects(List<String> subjects) {
        this.subjects = subjects;
    }
    
}

maven依赖

		<!-- 阿里fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.28</version>
        </dependency>

你可能感兴趣的:(JAVA,json,java,开发语言)