gpt4 book ai didi

java - 从一组 Java Pojo 类创建 JSON 结构

转载 作者:行者123 更新时间:2023-12-02 01:17:09 25 4
gpt4 key购买 nike

我需要从一组 java pojo 类创建一个 JSON 对象结构。只需查看 Json 文件,就可以更好地理解对象的结构。我尝试了 Gson 和 org.codehaus.jackson.map.ObjectMapper 库。但无法生成与 java pojo 对象中所有字段相关的所有 Json 标签。创建的 json 文件仅包含来自值设置对象的值。我需要在 Json 文件中包含 pojo 对象的所有字段。

Gson

        Hotel hotel = new Hotel(); //This hotel object includes multiple objects and those objects also include multiple objects, lists
Gson gson = new GsonBuilder().create();
String json = gson.toJson(hotel);
System.out.println(json);

对象映射器

ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(new File("/home/Pojos.json");

这是我得到的类和 json 响应。

酒店.java


package datatypes;

import java.util.ArrayList;
import java.util.List;

public class Hotel {


private String hotelCode;
private String chainCode;
private String hotelName;
private List<Room> rooms = new ArrayList<Room>();
private List<RoomRateRestriction> roomRateRestrictions
= new ArrayList<RoomRateRestriction>();


public String getHotelCode() {
return hotelCode;
}
public void setHotelCode(String hotelCode) {
this.hotelCode = hotelCode;
}
public String getChainCode() {
return chainCode;
}
public void setChainCode(String chainCode) {
this.chainCode = chainCode;
}
public String getHotelName() {
return hotelName;
}
public void setHotelName(String hotelName) {
this.hotelName = hotelName;
}
public List<Room> getRooms() {
return rooms;
}
public void setRooms(List<Room> rooms) {
this.rooms = rooms;
}

public void addRoom(Room room){
this.rooms.add(room);
}
public List<RoomRateRestriction> getRoomRateRestrictions() {
return roomRateRestrictions;
}
public void setRoomRateRestrictions(
List<RoomRateRestriction> roomRateRestrictions) {
this.roomRateRestrictions = roomRateRestrictions;
}

public void addRoomRateRestrictions(
RoomRateRestriction roomRateRestriction) {
this.roomRateRestrictions.add(roomRateRestriction);
}
}

JSON

   {
"rooms":[],
"roomRateRestrictions":[]
}

最佳答案

GsonBuilder() 上添加 serializeNulls() 以序列化 null 字段

Configure Gson to serialize null fields. By default, Gson omits all fields that are null * during serialization.

class Hotel {
private String name;
private List<Guest> guests = new ArrayList<>(Collections.singleton(new Guest())); //you have to set a value in order to get the structure of the Guest class otherwise it will show an empty list []
//getter setter
}

class Guest {
private String name;
//getter setter
}

Gson

 Hotel hotel = new Hotel();
Gson gson = new GsonBuilder().serializeNulls().create();
String json = gson.toJson(hotel);
System.out.println(json);

输出

{  
"name":null,
"guests":[
{
"name":null
}
]
}

关于java - 从一组 Java Pojo 类创建 JSON 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58371086/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com