我有类似的东西:
@Entity
@Table(name = "myEntity")
public class MyEntity {
//....
@Column(name = "content")
private byte[] content;
//....
}
问题: 我将MyEntity作为JSON字符串传递给客户端。 但问题是我有两种类型的客户请求:
在第一种情况下,我不需要@JsonIgnore注释,第二种 - 需要。
问题:
P.S。据我了解,即使我使用延迟加载注释标记 byte [] content 数组,当Jackson将MyEntity解析为JSON字符串时,它仍会被加载。
提前谢谢!
答案 0 :(得分:4)
您可以使用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"}
正如您所看到的,基本视图杰克逊没有阅读content
属性。
答案 1 :(得分:1)
据我所知,不可能让杰克逊懒得按需加载你的财产。也许另一种方法是创建另一个值对象,只需复制您想要的属性并删除您不想要的属性。