【发布时间】:2021-11-16 08:47:10
【问题描述】:
我正在做一个小项目。简而言之,我想通过序列化从列表中生成 JSON,但它的格式可能不正确。
这是主要参考代码。其他 3 个类只包含字符串,其中一个是枚举。
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.json.JsonWriteFeature;
import com.fasterxml.jackson.core.util.DefaultIndenter;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
List<Comment> comments = new ArrayList<>();
Comment comm = new Comment();
comm.setId("1");
comm.setUser("Zoli");
comm.setDate("2021/09/28");
comm.setDescription("Alma");
comments.add(comm);
Post post = new Post();
post.setId(1);
post.setTitle("Alma");
post.setUser("Soviet");
post.setDate("2021/09/28");
post.setStatus(Status.IN_PROGRESS);
post.setDescription("Sample Post");
post.setComments(comments);
ObjectMapper objectMapper = new ObjectMapper();
//objectMapper.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, false);
//objectMapper.configure(JsonGenerator.Feature.QUOTE_NON_NUMERIC_NUMBERS, false);
//objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
DefaultPrettyPrinter printer = new DefaultPrettyPrinter();
printer.indentArraysWith(new DefaultIndenter());
String serialized = objectMapper
.writerWithDefaultPrettyPrinter()
.writeValueAsString(post);
objectMapper.writeValue(new File("car.json"), serialized);
}
}
这段代码的输出:
"{\r\n \"id\" : 1,\r\n \"title\" : \"Alma\",\r\n \"user\" : \"Soviet\",\r\n \"date\" : \"2021/09/28\",\r\n \"status\" : \"IN_PROGRESS\",\r\n \"description\" : \"Sample Post\",\r\n \"comments\" : [Comment(id=1, user=Zoli, date=2021/09/28, description=Alma)]\r\n}"
我在寻找什么:
{
"posts" : [
{ "id": 1,
"title": "Example",
"user": "Ruben",
"date": "22/09/2021",
"status": "done",
"description": "Sample post",
"comments": [
{ "id": 1, "user": "Zoli", "date": "22/09/2021", "description": "Very nice!"},
{ "id": 2, "user": "Krisz", "date": "22/09/2021", "description": "Nice!"},
{ "id": 3, "user": "Csaba", "date": "22/09/2021", "description": "Very good!"},
{ "id": 4, "user": "Márk", "date": "22/09/2021", "description": "Good!"}
]
}
注释掉的是解决这个问题的尝试。
【问题讨论】:
标签: java json serialization jackson deserialization