一个案例让你学会_实体类与Json字符串互相转换
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; import com.lydms.domain.Person; public class Test { public static void main(String[] args) throws InterruptedException, JsonProcessingException { Person person = new Person(); person.setAge(15); person.setName("小明"); ObjectMapper mapper = new ObjectMapper(); String result = mapper.writeValueAsString(person); System.out.println(result); } }
运行结果:
3、Json转为实体类
import com.fasterxml.jackson.databind.ObjectMapper; import com.lydms.domain.Person; import java.io.IOException; public class Test { public static void main(String[] args) throws IOException { String str="{\"name\":\"小明\",\"age\":15}"; ObjectMapper mapper = new ObjectMapper(); Person person = mapper.readValue(str, Person.class); System.out.println("姓名为:"+person.getName()+",年龄为:"+person.getAge()); } }
运行结果: