gpt4 book ai didi

java - Spring序列化时如何忽略临时对象属性

转载 作者:行者123 更新时间:2023-11-30 07:52:53 25 4
gpt4 key购买 nike

我正在使用 spring 框架创建一个休息服务器。我有一个 Controller 类,可以通过 id 请求 itempattern 对象或获取所有对象。使用 Spring,我使用 @ResponseBody@RequestMapping(products = MediaType.APPLICATION_JSON_VALUE) 将对象序列化为 JSON。

我的 Controller 类:

@RestController
@RequestMapping("/rest/itempatterns")
public class ItempatternController {
/**
* injected resource service interface,
* loads objects from database
*/
private IItempatternResource resource;

/**
* GET one itempattern by the three identifier,
* URL: /rest/itempatterns/:id
*
* @param id
* @return
*/
@RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody Itempattern getTirepatternById(@PathVariable("id") int id) {
return resource.getById(id);
}

/**
* GET all itempatterns,
* URL: /rest/itempatterns
*
* @return
*/
@RequestMapping(value = "", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody List<Itempattern> getAllTirepatterns() {
return resource.getAll();
}

}

从资源中我可以接收一个 itempattern 对象,如下所示:

public class Itempattern implements Serializable {

private static final long serialVersionUID = -6168853991825655795L;

@JsonProperty("itemtype")
private Itemtype itemtype;

@JsonProperty("pattern")
private String patternXML;

public Itempattern() {
super();
}

public Itempattern(Itemtype itemtype, String patternXML) {
super();
this.itemtype = itemtype;
this.patternXML = patternXML;
}

//...getter and setter
}

问题是,属性 patternXML 是一个非常长的字符串,有时我想加载所有具有所有属性的 itempatterns,有时属性 patternXML 应该被忽略,而序列化(以节省网络资源)。例如,我想填充一个选择列表,并且不想加载所有对象及其 patternXML 属性(也许稍后单击时加载)。

在使用 @ResponseBody 进行序列化时,在某些情况下是否可以暂时忽略某个属性?

感谢您的帮助!

最佳答案

您可能正在寻找 Jackson 的 @JsonView特征。这样,您可以告诉某个请求映射生成具有所选属性集的序列化 JSON。

示例

public class View {
interface Summary {}
}

public class User {

@JsonView(View.Summary.class)
private Long id;

@JsonView(View.Summary.class)
private String firstname;

@JsonView(View.Summary.class)
private String lastname;

private String email;
private String address;
private String postalCode;
private String city;
private String country;
}

Controller

@RestController
public class MessageController {

@Autowired
private MessageService messageService;

@JsonView(View.Summary.class)
@RequestMapping("/messageSummaryOnly")
public List<Message> getAllMessages() {
return messageService.getAll();
}
}

请求/messageSummaryOnly将生成序列化列表,其中每个 Message只有填充的字段是那些用 @JsonView(View.Summary.class) 注释的字段

引用:https://spring.io/blog/2014/12/02/latest-jackson-integration-improvements-in-spring

关于java - Spring序列化时如何忽略临时对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33121786/

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