【问题标题】:how to limit the json fields while getting response in spring rest如何在spring rest中获得响应时限制json字段
【发布时间】:2016-07-08 14:37:36
【问题描述】:
this the code:

@RequestMapping(value="/find/city={city}", method=RequestMethod.GET)
public List<Master_City> getCity(@PathVariable String city)
 {
    return City_Repository.findByCityLikeIgnoreCase(city);
 }

显示所有 JSON 字段。我只需要 2 个字段。

【问题讨论】:

  • 同时响应:{“id”:“57731797c0d995a32aa15623”,“indexid”:65,“city”:“Barcelona”,“country”:{“id”:“576ced3ac0d911e15272d3f3”,“indexid” ": 136, "国家": "西班牙", "foundin": "{ \"expedia\" : 1 , \"hpo\" : 1}", "code": "{ \"expedia\" : 166} " }
  • 您的函数被编写为返回整个对象。与其返回 City_Repository,不如在函数内部创建一个数组,将需要的字段从 City_Repository 推送到数组中,然后返回数组而不是整个 City_Repository 对象。
  • 如果您使用的是 Jackson,那么 @JsonIgnoreProperties 可能会帮助您。

标签: java spring mongodb rest


【解决方案1】:

只需将@JsonIgnore 注释添加到您不想发送的字段的getter 示例:

class MasterCity{
 private String contact;
  private String address;
     public String getContact() {
    return contact;
}

public void setContact(String contact) {
    this.contact = contact;
}
@JsonIgnore
public String getAddress() {
    return address;
}

public void setAddress(String address) {
    this.address = address;
}
}


@RequestMapping(value="/find/city={city}", method=RequestMethod.GET)
public List<Master_City> getCity(@PathVariable String city)
 {
    return City_Repository.findByCityLikeIgnoreCase(city);
 }

现在它会忽略地址

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    • 1970-01-01
    • 2021-01-07
    • 1970-01-01
    相关资源
    最近更新 更多