@JsonRootName 不起作用

use*_*530 4 json jackson jakarta-ee

我有这个简单的 Java 实体,我需要使它成为 JSon 输出,我可以通过 e Web 服务实现它。

@Entity
@JsonRootName(value = "flights")
public class Flight implements Serializable {

@Transient
private static final long serialVersionUID = 1L;

public Flight() {
    super();
}

public Flight(FlightDestination destinationFrom, FlightDestination destinationTo, Integer flightPrice, Date date,
        Airplane airplaneDetail) {
    super();
    this.destinationFrom = destinationFrom;
    this.destinationTo = destinationTo;
    this.flightPrice = flightPrice;
    this.date = date;
    this.airplaneDetail = airplaneDetail;
}

public Flight(FlightDestination destinationFrom, FlightDestination destinationTo, Integer flightPrice, Date date) {
    super();
    this.destinationFrom = destinationFrom;
    this.destinationTo = destinationTo;
    this.flightPrice = flightPrice;
    this.date = date;
}

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;

@Enumerated(EnumType.STRING)
private FlightDestination destinationFrom;

@Enumerated(EnumType.STRING)
private FlightDestination destinationTo;

private Integer flightPrice;

@Temporal(TemporalType.DATE)
private Date date;

@OneToOne(cascade = { CascadeType.PERSIST, CascadeType.REMOVE })
@JoinColumn(name = "airplane_fk")
private Airplane airplaneDetail;}
Run Code Online (Sandbox Code Playgroud)

我添加了@JsonRootName,但我仍然以这种方式获得我的 json 输出:

    [  
      {   

      },

      { 

      }
   ]
Run Code Online (Sandbox Code Playgroud)

我还有什么要添加到我的实体,所以最后得到这种输出:

    {
     "flights":

     [  

      {   

      },

      { 

      }
    ]
   }
Run Code Online (Sandbox Code Playgroud)

var*_*ren 7

如果你想使用@JsonRootName(value = "flights")你必须设置适当的功能ObjectMapper

ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE); 
mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
Run Code Online (Sandbox Code Playgroud)

但是,因为List<Flight>这会产生

[  
  {"flights": {}},
  {"flights": {}},
  {"flights": {}},
]
Run Code Online (Sandbox Code Playgroud)

所以你可能必须创建包装对象:

public class FlightList {
    @JsonProperty(value = "flights")
    private ArrayList<Flight> flights;
}
Run Code Online (Sandbox Code Playgroud)

FlightList将有{"flights":[{ }, { }]}输出 json


小智 6

您可以使用以下注释来使用 Jackson 来制作包装器;

...
@JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT, use = JsonTypeInfo.Id.NAME)
@JsonTypeName("user")
public class LoginResponse {
  private String name;
  private String email;
}
Run Code Online (Sandbox Code Playgroud)

响应将是;

{
  "user": {
    "name": "Lucienne",
    "username": "asenocakUser"
  }
}
Run Code Online (Sandbox Code Playgroud)