@Test publicvoidTest1(){ JSONObject jsonObject = new JSONObject(); Person person = new Person("张三", "男", 20); String s = jsonObject.toJSONString(person); System.out.println(s);//{"age":20,"name":"张三","sex":"男"} }
由 JSON 字符串生成实体类:
1 2 3 4 5 6 7 8
//由Json字符串生成实体类 @Test publicvoidTest2(){ String json = "{\"sex\":\"男\",\"name\":\"张三\",\"age\":25}"; JSONObject jsonObject = new JSONObject(); Person person = jsonObject.parseObject(json, Person.class); System.out.println(person);//Person{name='张三', sex='男', age=25} }
@Test publicvoidTest1()throws JsonProcessingException { Person person = new Person("张三", "男", 20); ObjectMapper objectMapper = new ObjectMapper(); String s = objectMapper.writeValueAsString(person); System.out.println(s);//{"name":"张三","sex":"男","age":20} }
由 JSON 字符串生成实体类:
1 2 3 4 5 6 7 8 9
@Test publicvoidTest2()throws IOException { String json = "{\"sex\":\"男\",\"name\":\"张三\",\"age\":25}"; ObjectMapper objectMapper = new ObjectMapper(); //要确保Person类有无参构造方法,不然会报错 // com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.XX.Info` Person person = objectMapper.readValue(json, Person.class); System.out.println(person);//Person{name='张三', sex='男', age=25} }
GSON方式
导包:import com.google.gson.Gson;
由实体类生成 JSON 字符串:
1 2 3 4 5 6 7
@Test publicvoidTest1(){ Person person = new Person("张三", "男", 20); Gson gson = new Gson(); String s = gson.toJson(person); System.out.println(s);//{"name":"张三","sex":"男","age":20} }
由 JSON 字符串生成实体类:
1 2 3 4 5 6 7
@Test publicvoidTest2()throws IOException { Gson gson = new Gson(); String jsonContent = "{\"sex\":\"男\",\"name\":\"张三\",\"age\":25}"; Person person = gson.fromJson(jsonContent, Person.class); System.out.println(person);//Person{name='张三', sex='男', age=25} }
FastJSON方式
导包 import com.alibaba.fastjson.JSON;
由实体类生成 JSON 字符串:
1 2 3 4 5 6
@Test publicvoidTest1(){ Person person = new Person("张三", "男", 20); Object o = JSON.toJSON(person); System.out.println(o.toString());//{"sex":"男","name":"张三","age":20} }
由 JSON字符串生成实体类:
1 2 3 4 5 6
@Test publicvoidTest2()throws IOException { String json = "{\"sex\":\"男\",\"name\":\"张三\",\"age\":25}"; Person person = JSON.parseObject(json, Person.class); System.out.println(person);// }