一、Jackson方式
1、实体类
public class Person { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
2、实体类转为Json
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; public class Test { public static void main(String[] args) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); System.out.println("=============实体类转为Json============="); Person person = new Person(); person.setAge(15); person.setName("小明"); String result = mapper.writeValueAsString(person); System.out.println(result); System.out.println("=============Json转为实体类============="); String str = "{\"name\":\"小明\",\"age\":15}"; Person person1 = mapper.readValue(str, Person.class); System.out.println("姓名为:" + person1.getName() + ",年龄为:" + person1.getAge()); } }
3、运行结果
4、Spring boot中使用
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.beans.factory.annotation.Autowired; public class Test { @Autowired private ObjectMapper mapper; public void test() throws JsonProcessingException { System.out.println("=============实体类转为Json============="); Person person = new Person(); person.setAge(15); person.setName("小明"); String result = mapper.writeValueAsString(person); System.out.println(result); System.out.println("=============Json转为实体类============="); String str = "{\"name\":\"小明\",\"age\":15}"; Person person1 = mapper.readValue(str, Person.class); System.out.println("姓名为:" + person1.getName() + ",年龄为:" + person1.getAge()); } }
二、FastJson方式
1)、案例
1、Pom.xml
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.76</version> </dependency>
2、实体类
public class Person { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; }
3、实体类与Json转换
import com.alibaba.fastjson.JSON; public class Test { public static void main(String[] args) { System.out.println("=============实体类转为Json============="); Person person = new Person(); person.setAge(15); person.setName("小明"); String result = JSON.toJSONString(person); System.out.println(result); System.out.println("=============Json转为实体类============="); String str = "{\"name\":\"小明\",\"age\":15}"; Person person1 = JSON.parseObject(str, Person.class); System.out.println("姓名为:" + person1.getName() + ",年龄为:" + person1.getAge()); } }
4、运行结果