我有 4 个 POJO ( links )
我有一个类文件,它将根据这些 POJO 映射值 ( Link )
当我运行代码时
public static void main(String[] args) throws Exception {
Input user = new Input();
user.setId("0001");
user.setType("donut");
user.setName("cake");
user.setPpu(0.55);
下面是我的输出
{
"id" : "0001",
"type" : "donut",
"name" : "cake",
"ppu" : 0.55,
"batters" : null,
"topping" : [ ]
}
但是,我希望我的输出是
{ "id": "0001", "type": "donut", "name": "Cake", "ppu": 0.55, "batters":
{ "batter": [{ "id": "1001", "type": "Regular" },
{ "id": "1004", "type": "Devil's Food" } ] }, "topping": [{ "id": "5001",
"type": "None" }, { "id": "5004", "type": "Maple" } ] }
我不知道如何即兴编写代码来像我期望的那样打印输出,谢谢
预期:面糊、配料值也
最佳答案
你应该使用这样的东西:
public static void main(String[] args) throws Exception {
Input user = new Input();
user.setId("0001");
user.setType("donut");
user.setName("Cake");
user.setPpu(0.55);
// Add Regular batter
Batter batter1 = new Batter();
batter1.setId("0001");
batter1.setType("Regular");
// Add Devil's Food batter
Batter batter2 = new Batter();
batter2.setId("1004");
batter2.setType("Devil's Food");
Batters batters = new Batters();
batters.setBatter(Arrays.asList(batter1, batter2));
user.setBatters(batters);
// Add toppings
Topping topping1 = new Topping();
topping1.setId("5001");
topping1.setId("None");
Topping topping2 = new Topping();
topping2.setId("5004");
topping2.setId("Maple");
users.setTopping(Arrays.asList(topping1, topping2));
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
String json = mapper.writeValueAsString(user);
System.out.println(json); // expected string
关于java - 将 POJO 序列化为 JSON - 输入参数化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51792844/