springboot中json的使用_json image.png


在Springboot中可以使用如上的包来做json的处理

对象转字符串

ObjectMapper mapper = new ObjectMapper();

Staff obj = new Staff();

//Object to JSON in file

mapper.writeValue(new File("c:\file.json"), obj);

//Object to JSON in String

String jsonInString = mapper.writeValueAsString(obj);

字符串转对象

ObjectMapper mapper = new ObjectMapper();

String jsonInString = "{'name' : 'mkyong'}";

//JSON from file to Object

Staff obj = mapper.readValue(new File("c:\file.json"), Staff.class);

//JSON from URL to Object

Staff obj = mapper.readValue(new URL("http://mkyong.com/api/staff.json"), Staff.class);

//JSON from String to Object

Staff obj = mapper.readValue(jsonInString, Staff.class);

字符串转数组对象

转数组:

MyClass[] myObjects = mapper.readValue(json, MyClass[].class);

转list

List<MyClass> myObjects = mapper.readValue(jsonInput, new TypeReference<List<MyClass>>(){});

转特殊list

List<MyClass> myObjects = mapper.readValue(jsonInput, mapper.getTypeFactory().constructCollectionType(List.class, MyClass.class));