1. 程式人生 > >springMvc 將物件json返回時自動忽略掉物件中的特定屬性的註解方式

springMvc 將物件json返回時自動忽略掉物件中的特定屬性的註解方式

1.註解使用在 類名,介面頭上

@JsonIgnoreProperties(value={"comid"}) //希望動態過濾掉的屬性  

   @JsonIgnoreProperties(value={"comid"}) 
   public interface CompanyFilter{   
        }

2。該註解使用在get方法頭上

@JsonIgnore

   例

  @JsonIgnore
    public Integer getPageSize(){
           return Integer.valueOf(getRows()==null?"0":getRows().toString());
    }

-------------------------------

  • Jackson’s @JsonView is supported directly on @ResponseBody and ResponseEntity controller methods for serializing different amounts of detail for the same POJO (e.g. summary vs. detail page). This is also supported with View-based rendering by adding the serialization view type as a model attribute under a special key. See 
    the section called “Jackson Serialization View Support”
     for details. 
@RestController
public class UserController {

    @RequestMapping(path = "/user", method = RequestMethod.GET)
    @JsonView(User.WithoutPasswordView.class)
    public User getUser() {
        return new User("eric", "7!jd#h23");
    }
}


public class User {

    public interface WithoutPasswordView {};
    public interface WithPasswordView extends WithoutPasswordView {};

    private String username;
    private String password;

    public User() {
    }

    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }

    @JsonView(WithoutPasswordView.class)
    public String getUsername() {
        return this.username;
    }

    @JsonView(WithPasswordView.class)
    public String getPassword() {
        return this.password;
    }
}

---------- 然後在把他加入到model的過程 可以這麼寫
@Controller
public class UserController extends AbstractController {

    @RequestMapping(path = "/user", method = RequestMethod.GET)
    public String getUser(Model model) {
        model.addAttribute("user", new User("eric", "7!jd#h23"));
        model.addAttribute(JsonView.class.getName(), User.WithoutPasswordView.class);
        return "userView";
    }
}

------ 下面是測試
public static void main(String[] args) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    //建立物件
    User user = new User("user1","123456");
    //序列化
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    objectMapper.writerWithView(User.WithoutPasswordView.class).writeValue(bos, user);
    System.out.println(bos.toString());

    bos.reset();
    objectMapper.writerWithView(User.WithPasswordView.class).writeValue(bos, user);
    System.out.println(bos.toString());
}

輸出的答案是
{"username":"user1"}
{"username":"user1","password":"123456"}

------ 當然spring也有提供基於xml的配置方法,詳情看文件的內容 http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#mvc-ann-jsonview 也有人用aop的around中去過濾結果. ------------------------------- gson 版本

GSON 是Google釋出的 JSON 序列化/反序列化工具,非常容易使用。本文簡要討論在使用GSON將Java物件轉成JSON時,如何排除某些欄位。

最簡單的用法

假設有下面這個類:

class MyObj {

public int x;
public int y;

public MyObj(int x, int y) {
    this.x = x;
    this.y = y;
}

    }
最簡單的GSON用法如下所示:
@Test
    public void gson() {
        MyObj obj = new MyObj(1, 2);
        String json = new Gson().toJson(obj);
        Assert.assertEquals("{\"x\":1,\"y\":2}", json);
    }

方法1:排除transient欄位

這個方法最簡單,給欄位加上 transient 修飾符就可以了,如下所示: 

class MyObj {

public transient int x; // <---
public int y;

public MyObj(int x, int y) {
    this.x = x;
    this.y = y;
}

    }
@Test
    public void gson() {
        MyObj obj = new MyObj(1, 2);
        String json = new Gson().toJson(obj);
        Assert.assertEquals("{\"y\":2}", json); // <---
    }

方法2:排除Modifier為指定型別的欄位

這個方法需要用GsonBuilder定製一個GSON例項,如下所示:

class MyObj {

protected int x; // <---
public int y;

public MyObj(int x, int y) {
    this.x = x;
    this.y = y;
}

    }
@Test
    public void gson() {
Gson gson = new GsonBuilder()
.excludeFieldsWithModifiers(Modifier.PROTECTED) // <---
.create();

MyObj obj = new MyObj(1, 2);
String json = gson.toJson(obj); // <---
Assert.assertEquals("{\"y\":2}", json);
    }

方法3:使用@Expose註解

注意,沒有被 @Expose 標註的欄位會被排除,如下所示: 

class MyObj {

public int x;
@Expose public int y; // <---

public MyObj(int x, int y) {
    this.x = x;
    this.y = y;
}

    }
@Test
    public void gson() {
Gson gson = new GsonBuilder()
.excludeFieldsWithoutExposeAnnotation() // <---
.create();

MyObj obj = new MyObj(1, 2);
String json = gson.toJson(obj);
Assert.assertEquals("{\"y\":2}", json);
    }

方法4:使用ExclusionStrategy定製欄位排除策略

這種方式最靈活,下面的例子把所有以下劃線開頭的欄位全部都排除掉:

class MyObj {

public int _x; // <---
public int y;

public MyObj(int x, int y) {
    this._x = x;
    this.y = y;
}

    }
@Test
    public void gson() {
ExclusionStrategy myExclusionStrategy = new ExclusionStrategy() {

    @Override
    public boolean shouldSkipField(FieldAttributes fa) {
return fa.getName().startsWith("_");
    }

    @Override
    public boolean shouldSkipClass(Class<?> clazz) {
return false;
    }
    
};

Gson gson = new GsonBuilder()
.setExclusionStrategies(myExclusionStrategy) // <---
.create();

MyObj obj = new MyObj(1, 2);
String json = gson.toJson(obj);
Assert.assertEquals("{\"y\":2}", json);
    }