2019独角兽企业重金招聘Python工程师标准>>>
package Fasterxml; import com.fasterxml.jackson.databind.ObjectMapper; import mode.User; import java.io.StringWriter; import java.util.ArrayList; import java.util.List;/*** maven...**<dependency>* <groupId>com.fasterxml.jackson.core</groupId>* <artifactId>jackson-databind</artifactId>* <version>2.9.5</version>*</dependency>*/ public class ObjectMapperTest {public static void main(String[] args) {new ObjectMapperTest().objectToJson();new ObjectMapperTest().jsonToObject();new ObjectMapperTest().objectToJsonList();}void objectToJson(){ObjectMapper objectMapper = new ObjectMapper();try {User user = new User();user.setId(1000L);user.setName("tom");StringWriter stringWriter = new StringWriter();objectMapper.writeValue(stringWriter,user);System.out.println(stringWriter);} catch (Exception e) {e.printStackTrace();}}void jsonToObject(){ObjectMapper objectMapper = new ObjectMapper();try {String str = "{\"id\":1000,\"name\":\"tom\"}";User user = objectMapper.readValue(str,User.class);System.out.println(user.getName());} catch (Exception e) {e.printStackTrace();}}void objectToJsonList(){ObjectMapper objectMapper = new ObjectMapper();try {List list = new ArrayList();User user = new User();user.setId(1000L);user.setName("tom");User user2 = new User();user2.setId(2000L);user2.setName("jack");list.add(user);list.add(user2);StringWriter stringWriter = new StringWriter();objectMapper.writeValue(stringWriter,list);System.out.println(stringWriter);} catch (Exception e) {e.printStackTrace();}}}
console:
{"id":1000,"name":"tom"}
tom
[{"id":1000,"name":"tom"},{"id":2000,"name":"jack"}]