杰克逊,将普通的JSON数组反序列化为单个Java对象

时间:2017-11-28 23:11:44

标签: java json jackson jackson2 jackson-databind

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

1 个答案:

答案 0 :(得分:4)

您不需要def execute(self, context): execution_date = context.get("execution_date") ,只需使用@JsonCreator

@JsonFormat(shape = JsonFormat.Shape.ARRAY)

如果您需要在bean中保留一些备用字段声明顺序,请使用@JsonFormat(shape = JsonFormat.Shape.ARRAY) public static class Person { @JsonProperty private String firstName; @JsonProperty private String lastName; @JsonProperty private int age; }