如果 Json 与预期的对象结构不匹配,则通知 Jackson 抛出异常

Inform Jackson to throw exception if Json does not match expected object structure

使用此代码将 Json 转换为使用 Jackson 注释的 Java 对象:

import com.fasterxml.jackson.databind.ObjectMapper;
import objectmappertest.Request;
import java.io.IOException;

    public static void main(String args[]) throws IOException {
        final String json  = "{\"datePurchased\":\"2022-02-03 21:32:017\"},{\"unknownField\":\"test\"}";
        final Request request = mapper.readValue(json, Request.class);
        System.out.println("request : "+request);
    }

我预计会抛出一个异常,因为请求 Java 对象不包含字段类型 unknownField ,相反,Jackson 似乎从 JSON 解析它可以解析的内容。如果传递给 Jackson 的 Json 与 Java 对象结构不匹配,是否存在导致异常或设置标志的配置选项?

这是预期的结构:

import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.extern.jackson.Jacksonized;
import java.util.Date;

@Builder
@ToString
@Getter
@Setter
@Jacksonized
public class Request
{
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:sss")
    private final Date datePurchased;
}
 

FAIL_ON_UNKNOWN_PROPERTIES

Feature that determines whether encountering of unknown properties (ones that do not map to a property, and there is no "any setter" or handler that can handle it) should result in a failure (by throwing a JsonMappingException) or not.

使用示例:

   ObjectMapper mapper  = new ObjectMapper();
   mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);

文档:

https://fasterxml.github.io/jackson-databind/javadoc/2.6/com/fasterxml/jackson/databind/DeserializationFeature.html


您还可以在 POJO 本身之上使用注释 @JsonIgnoreProperties:但是我不太确定这是否会自行抛出异常。

@Target(value={ANNOTATION_TYPE,TYPE,METHOD,CONSTRUCTOR,FIELD})
@Retention(value=RUNTIME)
public @interface JsonIgnoreProperties
Annotation that can be used to either suppress serialization of properties (during serialization), or ignore processing of JSON properties read (during deserialization).

示例:

 // To throw exception on any unknown properties in JSON input:
 @JsonIgnoreProperties
 public class YourPoJo{
        
 }

public abstract boolean ignoreUnknown

Property that defines whether it is ok to just ignore any unrecognized properties during deserialization.

If true, all properties that are unrecognized -- that is, there are no setters or creators that accept them -- are ignored without warnings (although handlers for unknown properties, if any, will still be called) without exception.

Does not have any effect on serialization.

Default: false

文档:http://fasterxml.github.io/jackson-annotations/javadoc/2.7/com/fasterxml/jackson/annotation/JsonIgnoreProperties.html