簡體   English   中英

澤西休息服務器 - 如果值為0,則排除json響應中的整數

[英]Jersey rest server - Exclude integer in json response if value is 0

讓我說我有這個代碼用於在我的休息api中創建一個人。

@XmlRootElement    
public class Person
{
    int personId, departmentId;
    String name;
}


@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response create(Person person)
{
    createPerson(person);
    Person p = new Person();
    p.setPersonId(p.getPersonId());
    p.setName(p.getName());
    return Response.status(Response.Status.CREATED).entity(p).build();
}

響應示例:

{
    "departmentId" : 0,
    "personId" : 4335,
    "name" : "John Smith"
}

我只想在響應對象中返回personId和name參數。 我在這個例子中如何排除departmentId。

使用Integer並將其作為實例變量,如果未設置則為null。 然后你的json marshaller會忽略它。

如果您使用Jackson進行編組,則可以使用JsonInclude批注:

@XmlRootElement
public class Person{

  @JsonProperty
  int personId;

  @JsonInclude(Include.NON_DEFAULT)
  @JsonProperty
  int departmentId;

  @JsonProperty
  String name;

}

如果屬性值為0(默認為int),則使用Include.NON_DEFAULT將排除屬性,即使它是基元。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM