1

一个外部服务正在提供一个带有普通/原始元素的 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]

4

1 回答 1

5

你不需要@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;
}

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

于 2017-11-29T01:04:56.553 回答