【问题标题】:Jackson, deserialize plain JSON array to a single Java objectJackson,将纯 JSON 数组反序列化为单个 Java 对象
【发布时间】:2017-11-28 23:11:43
【问题描述】:

外部服务正在提供一个带有普通/原始元素的 JSON 数组(因此没有字段名称,也没有嵌套的 JSON 对象)。例如:

["Foo", "Bar", 30]

我想使用 Jackson 将其转换为以下 Java 类的实例:

class Person {
    private String firstName;
    private String lastName;
    private int age;

    Person(String firstName, String lastName, int age) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }
}

(这个类可以根据需要进行调整。)

问题:是否可以使用类似的方法将此 JSON 反序列化为 Java?

Person p = new ObjectMapper().readValue(json, Person.class);

或者这是否只能通过为这个 Person 类编写自定义 Jackson 反序列化器来实现?

我确实尝试了以下方法,但没有奏效:

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

public class Person {
    private String firstName;
    private String lastName;
    private int age;

    @JsonCreator
    public Person(
            @JsonProperty(index = 0) String firstName, 
            @JsonProperty(index = 1) String lastName, 
            @JsonProperty(index = 2) int age) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }

    public static void main(String[] args) throws IOException {
        String json = "[\"Foo\", \"Bar\", 30]";
        Person person = new ObjectMapper().readValue(json, Person.class);
        System.out.println(person);
    }
}

结果:Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Argument #0 of constructor [constructor for Person, annotations: {interface com.fasterxml.jackson.annotation.JsonCreator=@com.fasterxml.jackson.annotation.JsonCreator(mode=DEFAULT)}] has no property name annotation; must have name when multiple-parameter constructor annotated as Creator at [Source: (String)"["Foo", "Bar", 30]"; line: 1, column: 1]

【问题讨论】:

    标签: java json jackson jackson2 jackson-databind


    【解决方案1】:

    您不需要@JsonCreator,只需使用@JsonFormat(shape = JsonFormat.Shape.ARRAY)

    @JsonFormat(shape = JsonFormat.Shape.ARRAY)
    public static class Person {
        @JsonProperty
        private String firstName;
        @JsonProperty
        private String lastName;
        @JsonProperty
        private int age;
    }
    

    如果您需要在 bean 中保留一些替代字段声明顺序,请使用 @JsonPropertyOrder({"firstName", "lastName", "age" } )

    【讨论】:

      猜你喜欢
      • 2018-06-02
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 2018-07-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多