1. 对象转json:
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; public class TestJsonAndObject { /** * 对象转化为json * @throws JsonProcessingException */ @Test public void ObjectToJson() throws JsonProcessingException{ //引入Jackson Json处理工具包 User user = new User(); user.setId(1); user.setName("Tom"); user.setAge(18); user.setSex("男");
ObjectMapper objectMapper = new ObjectMapper(); //转化时其实调用的是对象身上的get方法 String json = objectMapper.writeValueAsString(user); System.out.println(json); } }
输出:{"id":1,"name":"Tom","age":18,"sex":"男"}
2. json转对象:
@Test public void jsonToObject() throws JsonParseException, JsonMappingException, IOException{ String json = "{"id":1,"name":"Tom","age":18,"sex":"男"}"; ObjectMapper objectMapper = new ObjectMapper(); User user = objectMapper.readValue(json, User.class); System.out.println(user); } 输出:User [id=1, name=Tom, age=18, sex=男]
3. 复杂格式转 :
@Test
public void jsonOA() throws IOException{ /** * 1.将多个对象转化为json */ List<User> userList = new ArrayList<>(); User user1 = new User(); user1.setId(1); user1.setName("Tom"); user1.setAge(18); user1.setSex("男"); User user2 = new User(); user2.setId(2); user2.setName("TomAA"); user2.setAge(19); user2.setSex("女"); userList.add(user1); userList.add(user2); ObjectMapper objectMapper = new ObjectMapper(); String json = objectMapper.writeValueAsString(userList); System.out.println(json); /** * 2.将复杂格式的json转化为对象,List集合 */ // List<User> user = objectMapper.readValue(json, userList.getClass()); //报警告... // System.out.println(user);
//不报警告...
User[] users = objectMapper.readValue(json, User[].class);
//将数组转化为list
List<User> asList = Arrays.asList(users);
System.out.println(asList);
}
输出1:[{"id":1,"name":"Tom","age":18,"sex":"男"},{"id":2,"name":"TomAA","age":19,"sex":"女"}]
输出2:[{id=1, name=Tom, age=18, sex=男}, {id=2, name=TomAA, age=19, sex=女}]
输出3,不报警告:[User [id=1, name=Tom, age=18, sex=男], User [id=2, name=TomAA, age=19, sex=女]]