您可以使用Jackson 视图。请看我下面的例子:
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
属性。