我有类似的东西:
@Entity
@Table(name = "myEntity")
public class MyEntity {
//....
@Column(name = "content")
private byte[] content;
//....
}
问题: 我将 MyEntity 作为 JSON 字符串传递给客户端。 但问题是我有两种类型的客户请求:
- 我需要传递 MyEntity 与 byte[] content 数组
- 我需要传递 MyEntity 不带 byte[] content 数组
在第一种情况下,我不需要 @JsonIgnore 注释,在第二种情况下 - 需要。
问题:
- 如何实现动态@JsonIgnore注解?这可能吗?
- 有什么替代方法可以实现延迟加载吗?
附注据我了解,即使我使用延迟加载注释标记我的 byte[] content 数组,当 Jackson 将 MyEntity 解析为 JSON 字符串时,它仍然会被加载。
提前谢谢您!
最佳答案
您可以使用Jackson views 。请看我下面的例子:
import java.io.IOException;
import java.util.Arrays;
import com.fasterxml.jackson.annotation.JsonView;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonProgram {
public static void main(String[] args) throws IOException {
Entity entity = new Entity();
entity.setId(100);
entity.setContent(new byte[] { 1, 2, 3, 4, 5, 6 });
ObjectMapper objectMapper = new ObjectMapper();
System.out.println("Generate JSON with basic properties: ");
System.out.println(objectMapper.writerWithView(View.BasicView.class).writeValueAsString(entity));
System.out.println("Generate JSON with all properties: ");
System.out.println(objectMapper.writerWithView(View.ExtendedView.class).writeValueAsString(entity));
}
}
interface View {
interface BasicView {
}
interface ExtendedView extends BasicView {
}
}
class Entity {
@JsonView(View.BasicView.class)
private int id;
@JsonView(View.ExtendedView.class)
private byte[] content;
public byte[] getContent() {
System.out.println("Get content: " + Arrays.toString(content));
return content;
}
public void setContent(byte[] content) {
this.content = content;
}
public int getId() {
System.out.println("Get ID: " + id);
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "Entity [id=" + id + ", content=" + Arrays.toString(content) + "]";
}
}
以上程序打印:
Generate JSON with basic properties:
Get ID: 100
{"id":100}
Generate JSON with all properties:
Get ID: 100
Get content: [1, 2, 3, 4, 5, 6]
{"id":100,"content":"AQIDBAUG"}
如您所见,使用基本 View Jackson 不会读取 content
属性。
关于json - 通过动态 @JsonIgnore 注释按需延迟加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61169360/