我有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" } ] }
我不确定如何才能即兴编写代码以输出期望的输出,谢谢
期望的:击球手,浇头的值也
答案 0 :(得分:1)
您应该使用类似以下的内容:
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
答案 1 :(得分:0)
public static void main(String[] args) throws JsonProcessingException {
Javabelazy user = new Javabelazy();
user.setId("0001");
user.setType("donut");
user.setName("Cake");
user.setPpu("0.55");
Batter batter1 = new Batter();
batter1.setId("0001");
batter1.setType("Regular");
Batter batter2 = new Batter();
batter2.setId("1004");
batter2.setType("Devil's Food");
Batters batters = new Batters();
Batter[] batter = new Batter[2];
batter[1] = batter1;
batter[0] = batter2;
batters.setBatter(batter );
user.setBatters(batters);
Topping topping1 = new Topping();
topping1.setId("5001");
topping1.setId("None");
Topping topping2 = new Topping();
topping2.setId("5004");
topping2.setId("Maple");
Topping[] topping = new Topping[2];
topping[0] = topping1;
topping[1] = topping2;
user.setTopping(topping );
ObjectMapper objectmapper = new ObjectMapper();
String json = objectmapper.writeValueAsString(user);
System.out.println(json);
}