Java Jackson JSON输出格式
我有一个Java Jackson JSON输出格式,java,json,jackson,Java,Json,Jackson,我有一个ArrayList,其中包含一些Person类型对象。Person类的getter和setter具有以下属性: private int id; private String name; private String email; private LocalDate birthDate; 我想以完全相同的格式将ArrayList导出为JSON输出文件: persons.json: [ { "id": 1, "name": "The Best", "email"
ArrayList
,其中包含一些Person
类型对象。Person
类的getter和setter具有以下属性:
private int id;
private String name;
private String email;
private LocalDate birthDate;
我想以完全相同的格式将ArrayList
导出为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"
}
]
我试图从ArrayList
创建数组
,并从该数组
创建输出,但我遇到了一个无法解决的问题。我正在获取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库。我也不允许在类中更改属性类型。如果我没记错的话,Jackson使用变异子创建JSON。在getBirthDate
mutator中,使用SimpleDateFormatter
或多种文本格式化程序之一返回格式化日期
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
}
}
您可以使用
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));
}
所以如果不允许添加的maven依赖项
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.4.0</version>
</dependency>
它将日期解析为:
{
"date": "2018-08-23"
}
如果您不想编写自定义序列化程序,另一种选择是使用@JsonGetter注释,但您应该将@JsonIgnore添加到birthDate字段,或者将值作为@JsonGetter的相同名称(“sameAsFieldName”)。如果将另一个值赋予@JsonGetter,而不将@JsonIgnore添加到字段中,则会序列化字段和@JsonGetter返回值
您可以按如下方式向类中添加方法:
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();
}
}
}
@JsonGetter("birthDate")
public String getSerializedLocalDate() {
return DateTimeFormatter.ofPattern("yyyy-MM-dd").format(this.getBirthDate());
}
除了core、annotations和databind之外,我不允许使用任何其他Jackson库。允许您将字段类型从LocalDate更改为其他类型吗?很遗憾,不允许。为什么不允许您使用其他Jackson库。这是什么胡说八道的政策?OP不允许使用jackson maven dependency JSR310是否无法仅向相关字段添加注释,并为此提供序列化程序?@WalterTross当然,您可以向字段添加
@JsonSerialize
注释并更改JsonSerializer
。但对于我们的示例LocalDate,如果我们给出JsonSerializer
并将序列化方法重写为jgen.writeStringField(“日期”,DateTimeFormatter.of模式(“yyyy-MM-dd”).format(value.getBirthDate())
,序列化的person包括{“birthDate”:{“date”:“2018-08-24”}
,它不是期望的输出。如果我们只序列化jgen.writeString(DateTimeFormatter.ofPattern(“yyyy-MM-dd”).format(value.getBirthDate())代码>序列化时在运行时抛出异常。谢谢,但应该有更简单的方法。无论如何,如果我是,我会编辑答案you@WalterTross我使用JsonGetter添加了另一个替代解决方案。因此,您不必编写自定义序列化程序。但是有一些要点需要考虑,这给了我相同的格式,比如在提供的例子中,代码<代码> JSON<代码>。
@JsonGetter("birthDate")
public String getSerializedLocalDate() {
return DateTimeFormatter.ofPattern("yyyy-MM-dd").format(this.getBirthDate());
}
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.");
}