【问题标题】:@JsonRootName not working@JsonRootName 不起作用
【发布时间】:2016-07-06 13:49:44
【问题描述】:

我有这个简单的 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;}

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

    [  
      {   

      },

      { 

      }
   ]

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

    {
     "flights":

     [  

      {   

      },

      { 

      }
    ]
   }

【问题讨论】:

    标签: json jakarta-ee jackson


    【解决方案1】:

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

    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE); 
    mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
    

    但是,对于List<Flight>,这将产生

    [  
      {"flights": {}},
      {"flights": {}},
      {"flights": {}},
    ]
    

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

    public class FlightList {
        @JsonProperty(value = "flights")
        private ArrayList<Flight> flights;
    }
    

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

    【讨论】:

    【解决方案2】:

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

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

    回复将是;

    {
      "user": {
        "name": "Lucienne",
        "username": "asenocakUser"
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-06
      • 1970-01-01
      • 1970-01-01
      • 2018-12-20
      • 1970-01-01
      • 2016-03-13
      相关资源
      最近更新 更多