Java对象与JSON字符串的相互转换

 1、测试代码如下:

package com.hjp.test;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hjp.DO.Person;
import org.junit.Test;
public class Json {
    @Test
    public void test02() {
        // 创建对象(嵌套两层)
        Person person = new Person("hjp", 20000, 22, "男", "area", new Person("lcr", 20000, 22, "男", "area"));
        // 将对象转为json字符串方法
        String jsonString = JSONObject.toJSONString(person);
        System.out.println("jsonString = " + jsonString);
        // 将json字符串转化为对象
        Person parseObject = JSON.parseObject(jsonString, Person.class);
        // 验证:嵌套格式的json字符串被全部转为对象格式
        String name = parseObject.getPerson().getName();
        System.out.println("name = " + name);
    }
}

2、使用到的实体

import lombok.Data;

@Data
public class Person {
    private String name;  // 姓名
    private int salary; // 薪资
    private int age; // 年龄
    private String sex; //性别
    private String area;  // 地区

    private Person person;// 嵌套对象(Person)

    // 构造方法
    public Person() {
    }

    public Person(String name, int salary, int age, String sex, String area) {
        this.name = name;
        this.salary = salary;
        this.age = age;
        this.sex = sex;
        this.area = area;
    }

    public Person(String name, int salary, int age, String sex, String area, Person person) {
        this.name = name;
        this.salary = salary;
        this.age = age;
        this.sex = sex;
        this.area = area;
        this.person = person;
    }
}

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