Jackson JSON输出格式

时间:2018-08-23 20:24:28

标签: java json jackson

我有一个ArrayList<Person>,其中包含一些Person类型的对象。 Person类具有其getter和setter的以下属性:

private int id;
private String name;
private String email;
private LocalDate birthDate;

我想以完全相同的格式将ArrayList<Person>导出到JSON输出文件中: persons.json

[
  {
    "id": 1,
    "name": "The Best",
    "email": "thenextbigthing@gmail.com",
    "birthDate": "1981-11-23"
  },
  {
    "id": 2,
    "name": "Andy Jr.",
    "email": "usa@gmail.com",
    "birthDate": "1982-12-01"
  },
  {
    "id": 3,
    "name": "JohnDoe",
    "email": "gameover@gmail.com",
    "birthDate": "1990-01-02"
  },
  {
    "id": 4,
    "name": "SomeOne",
    "email": "rucksack@gmail.com",
    "birthDate": "1988-01-22"
  },
  {
    "id": 5,
    "name": "Mr. Mxyzptlk",
    "email": "bigman@hotmail.com",
    "birthDate": "1977-08-12"
  }
]

我尝试从Array创建一个ArrayList,并从该Array创建输出,但是我有一个问题,无法解决。我正在获取birthDate属性的输出数据,如下所示:

"birthDate" : {
    "year" : 1952,
    "month" : "JANUARY",
    "chronology" : {
      "id" : "ISO",
      "calendarType" : "iso8601"
    },
    "era" : "CE",
    "leapYear" : true,
    "dayOfMonth" : 27,
    "monthValue" : 1,
    "dayOfWeek" : "SUNDAY",
    "dayOfYear" : 27
  }

如何使每个属性的输出格式与示例persons.json输出文件中提供的格式相同。除了核心,注释和数据绑定,我不允许使用任何其他Jackson库。我也不允许在类内部更改属性类型。

4 个答案:

答案 0 :(得分:3)

因此,如果您不允许添加

的maven依赖项
<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
    <version>2.4.0</version>
</dependency>

然后您可以为您的课程编写自定义序列化程序,如下所示:

public class MyCustomSerializer extends JsonSerializer<Person> {

    @Override
    public void serialize(Person value, JsonGenerator jgen,
                          SerializerProvider provider) throws IOException,
            JsonProcessingException {
        if (value != null) {
            jgen.writeStartObject();

            jgen.writeStringField("date", DateTimeFormatter.ofPattern("yyyy-MM-dd").format(value.getBirthDate()));
            // parse other fields here manually

            jgen.writeEndObject();
        }
    }
}

并将以下注释添加到您的Person.class:

@JsonSerialize(using = MyCustomSerializer.class)

它将日期解析为:

{
    "date": "2018-08-23"
}

如果您不想编写自定义序列化程序,另一种替代方法是使用@JsonGetter批注,但您应该在@DateDate字段中添加@JsonIgnore或为@JsonGetter(“ sameAsFieldName”)赋予相同的名称。如果您给@JsonGetter提供另一个值,并且不将@JsonIgnore添加到您的字段中,则会序列化您的字段和@JsonGetter返回值。

您可以按如下所示将方法添加到您的类中:

@JsonGetter("birthDate")
public String getSerializedLocalDate() {
    return DateTimeFormatter.ofPattern("yyyy-MM-dd").format(this.getBirthDate());
}

答案 1 :(得分:0)

如果我没记错的话,Jackson使用变异器来创建JSON。在getBirthDate转换器中,使用SimpleDateFormatter或许多Text格式化程序之一返回格式化日期。

class Person {
   private int id;
   private String name;
   private String email;
   private LocalDate birthDate;

   // MUTATORS HERE


   @JsonProperty("birthDate")
   public String getStringBirthDate(){
      // Turn to formatted (yyyy-mm-dd) String
   } 
}

答案 2 :(得分:0)

public void saveListToJSON(String fileName) throws
            MyCustomException {

        DateTimeFormatter dtf
        = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        ObjectNode newStud;
        int id;
        String name;
        String email;
        String birthDate;

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
        ArrayNode root = objectMapper.createArrayNode();

        for (Person person : this.persons) {
            newStud = objectMapper.createObjectNode();
            id = person.getId();
            name = person.getName();
            email = person.getEmail();
            birthDate = person.getBirthDate().format(dtf);
            newStud.put("id", id);
            newStud.put("name", name);
            newStud.put("email", email);
            newStud.put("birthDate", birthDate);
            root.add(newStud);
        }

        try {
            objectMapper.writeValue(new File(fileName), root);
        } catch (IOException ex) {
            throw new MyCustomException("The given output file "
                    + fileName + " cannot be opened for writing.");
        }

答案 3 :(得分:-1)

您可以使用ObjectMapper

public static void main(String[] args) throws IOException {
    ObjectMapper mapper = new ObjectMapper();

    // to enable java.time serializing
    mapper.registerModule(new JavaTimeModule());
    mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    // just to format output
    mapper.enable(SerializationFeature.INDENT_OUTPUT);

    // JSON - your provided JSON file
    Person[] arrayList
            = mapper.readValue(JSON, Person[].class);

    System.out.println(mapper.writeValueAsString(arrayList));
}