简体   繁体   English

如何在属性中使用Lombok定义JSON:@JsonPropertyOrder和@JsonIgnore(JAVA)

[英]How to define JSON with Lombok in properties: @JsonPropertyOrder and @JsonIgnore (JAVA)

I'm trying to use lombok with JSON but I have some hiccups 我正在尝试将lombok与JSON一起使用,但出现了一些问题

Json is not respecting the order when the name of the variable is different from @JsonProperty. 当变量名称不同于@JsonProperty时,Json不遵守顺序。

(it's probably a problem with the getters) (这可能是吸气剂的问题)

Another point is that I would like to hide the id of the Object1 in the generated json 另一点是,我想在生成的json中隐藏Object1的ID

@Data
@Builder(toBuilder = true)
@AllArgsConstructor(access = AccessLevel.PACKAGE)
@NoArgsConstructor(access = AccessLevel.PACKAGE)
@JsonPropertyOrder({ "id", "objectid", "value" })
public class Object1 {

@JsonIgnore
private Long id;

@JsonProperty("objectid")
private Long subid;

@JsonProperty("value")
private String value;

}

Result: 结果:

{
  "id" : 123,  <--- I want to hide
  "value" : "...",
  "objectid" : 123
}

"this is a small and fictional class" “这是一个虚构的小类”

Thanks, 谢谢,

To solve the output order try to use ObjectMapper like this: 要解决输出顺序,请尝试使用ObjectMapper如下所示:

ObjectMapper om = new ObjectMapper();
String jsonString = om.writeValueAsString(myObject1);
System.out.println(jsonString);

To hide the id you can use this jackson annotation: 要隐藏ID,您可以使用以下杰克逊注释:

@JsonIgnoreProperties(value = {"id"})

If you still want to be able to set the id using setter add this member to the annotation: 如果您仍然希望能够使用setter设置ID,请将此成员添加到注释中:

allowSetters = true

Your code works fine... What do you want to get in result? 您的代码工作正常...您想得到什么? 您的密码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM