ObjectMapper常见用法(Intro to the Jackson ObjectMapper)

maven依赖

xml 复制代码
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.14.2</version>
</dependency>
java 复制代码
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Car {
    private String color;
    private String type;
}

Java Object to JSON

java 复制代码
ObjectMapper objectMapper = new ObjectMapper();

Car car = new Car("yellow", "renault");

objectMapper.writeValue(new File("D:/projects/tutorails_kanomoku/business-prac/src/main/java/atomicitybusiness/method/output/car.json"), car);

以下内容输出到文件

java 复制代码
{"color":"yellow","type":"renault"}
java 复制代码
ObjectMapper objectMapper = new ObjectMapper();

Car car = new Car("yellow", "renault");

String carAsString = objectMapper.writeValueAsString(car);

// {"color":"yellow","type":"renault"}

JSON to Java Object

java 复制代码
ObjectMapper objectMapper = new ObjectMapper();

Car car = objectMapper.readValue(new URL("file:D:/projects/tutorails_kanomoku/business-prac/src/main/java/atomicitybusiness/method/output/car.json"), Car.class);

System.out.println(car); 
// Car(color=Black, type=BMW)
java 复制代码
ObjectMapper objectMapper = new ObjectMapper();

Car car = objectMapper.readValue(new File("D:/projects/tutorails_kanomoku/business-prac/src/main/java/atomicitybusiness/method/output/car.json"), Car.class);

System.out.println(car); 
// Car(color=Black, type=BMW)
java 复制代码
ObjectMapper objectMapper = new ObjectMapper();

String json = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }";

Car car = objectMapper.readValue(json, Car.class);
System.out.println(car); // Car(color=Black, type=BMW)

JSON to Jackson JsonNode

java 复制代码
ObjectMapper objectMapper = new ObjectMapper();

String json = "{ \"color\" : \"Black\", \"type\" : \"FIAT\" }";

JsonNode jsonNode = objectMapper.readTree(json);

String color = jsonNode.get("color").asText();
System.out.println(color); // Black

Creating a Java List From a JSON Array String

java 复制代码
ObjectMapper objectMapper = new ObjectMapper();

String jsonCarArray = "[{ \"color\" : \"Black\", \"type\" : \"BMW\" }, { \"color\" : \"Red\", \"type\" : \"FIAT\" }]";

List<Car> listCar = objectMapper.readValue(jsonCarArray, new TypeReference<List<Car>>() {});

System.out.println(listCar); 
// [Car(color=Black, type=BMW), Car(color=Red, type=FIAT)]

Creating Java Map From JSON String

java 复制代码
ObjectMapper objectMapper = new ObjectMapper();

String json = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }";

Map<String, Object> map = objectMapper.readValue(json, new TypeReference<Map<String, Object>>() {});

System.out.println(map); 
// {color=Black, type=BMW}

Configuring Serialization or Deserialization Feature

java 复制代码
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = "{ \"color\" : \"Black\", \"type\" : \"Fiat\", \"year\" : \"1970\" }";

objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Car car = objectMapper.readValue(jsonString, Car.class);
System.out.println(car); // Car(color=Black, type=Fiat)

JsonNode jsonNodeRoot = objectMapper.readTree(jsonString);
JsonNode jsonNodeYear = jsonNodeRoot.get("year");
String year = jsonNodeYear.asText();
System.out.println(year); // 1970

objectMapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false);

objectMapper.configure(DeserializationFeature.FAIL_ON_NUMBERS_FOR_ENUMS, false);

Creating Custom Serializer or Deserializer

java 复制代码
public class CustomCarSerializer extends StdSerializer<Car> {

    public CustomCarSerializer() {
        this(null);
    }

    public CustomCarSerializer(Class<Car> t) {
        super(t);
    }

    @Override
    public void serialize(Car car, JsonGenerator jsonGenerator, SerializerProvider serializer) throws IOException {
        jsonGenerator.writeStartObject();
        jsonGenerator.writeStringField("car_brand", car.getType());
        jsonGenerator.writeEndObject();
    }
}
java 复制代码
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule("CustomCarSerializer", new Version(1, 0, 0, null, null, null));
module.addSerializer(Car.class, new CustomCarSerializer());
mapper.registerModule(module);

Car car = new Car("yellow", "renault");

String carJson = mapper.writeValueAsString(car);
System.out.println(carJson); 
// {"car_brand":"renault"}
java 复制代码
public class CustomCarDeserializer extends StdDeserializer<Car> {

    public CustomCarDeserializer() {
        this(null);
    }

    public CustomCarDeserializer(Class<?> vc) {
        super(vc);
    }

    @Override
    public Car deserialize(JsonParser parser, DeserializationContext deserializer) throws IOException {
        Car car = new Car();
        ObjectCodec codec = parser.getCodec();
        JsonNode node = codec.readTree(parser);
        JsonNode colorNode = node.get("color");
        String color = colorNode.asText();
        car.setColor(color);
        return car;
    }
}
java 复制代码
String json = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }";

ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule("CustomCarDeserializer", new Version(1, 0, 0, null, null, null));
module.addDeserializer(Car.class, new CustomCarDeserializer());
mapper.registerModule(module);

Car car = mapper.readValue(json, Car.class);
System.out.println(car); // Car(color=Black, type=null)

Handling Date Formats

Read More Jackson Date

java 复制代码
public class Request 
{
    private Car car;
    private Date datePurchased;

    // standard getters setters
}
java 复制代码
ObjectMapper objectMapper = new ObjectMapper();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm a z");
objectMapper.setDateFormat(df);
String carAsString = objectMapper.writeValueAsString(request);
// output: {"car":{"color":"yellow","type":"renault"},"datePurchased":"2016-07-03 11:43 AM CEST"}

-----------------------------------------------------------------------------读书笔记摘自 文章:Intro to the Jackson ObjectMapper

相关推荐
魔道不误砍柴功13 分钟前
Java 中如何巧妙应用 Function 让方法复用性更强
java·开发语言·python
_.Switch38 分钟前
高级Python自动化运维:容器安全与网络策略的深度解析
运维·网络·python·安全·自动化·devops
2401_8504108338 分钟前
文件系统和日志管理
linux·运维·服务器
XMYX-01 小时前
使用 SSH 蜜罐提升安全性和记录攻击活动
linux·ssh
测开小菜鸟2 小时前
使用python向钉钉群聊发送消息
java·python·钉钉
萧鼎3 小时前
Python并发编程库:Asyncio的异步编程实战
开发语言·数据库·python·异步
弗锐土豆3 小时前
Windows系统中Oracle VM VirtualBox的安装
windows·虚拟机·virtualbox
学地理的小胖砸3 小时前
【一些关于Python的信息和帮助】
开发语言·python
疯一样的码农3 小时前
Python 继承、多态、封装、抽象
开发语言·python
秋の花3 小时前
【JAVA基础】Java集合基础
java·开发语言·windows