View Javadoc
1   package cn.home1.oss.lib.common;
2   
3   import com.google.gson.Gson;
4   import com.google.gson.GsonBuilder;
5   import com.google.gson.JsonDeserializer;
6   import com.google.gson.JsonPrimitive;
7   import com.google.gson.JsonSerializer;
8   
9   import org.springframework.security.core.GrantedAuthority;
10  import org.springframework.security.core.authority.SimpleGrantedAuthority;
11  
12  /**
13   * TODO remove all SimpleGrantedAuthority.
14   * Created by Meifans on 17/1/9.
15   */
16  public final class GsonUtils {
17  
18    public static Gson setup(final GsonBuilder builder) {
19      return builder
20        .registerTypeAdapter(GrantedAuthority.class, getAuthoritySerializer())
21        .registerTypeAdapter(GrantedAuthority.class, getAuthorityDeSerializer()).create();
22    }
23  
24    private static JsonDeserializer<GrantedAuthority> getAuthorityDeSerializer() {
25      return (json, typeOfT, context) -> //
26        new SimpleGrantedAuthority(json.getAsString());
27    }
28  
29    private static JsonSerializer<GrantedAuthority> getAuthoritySerializer() {
30      return (authority, typeOfSrc, context) -> new JsonPrimitive(authority.getAuthority());
31    }
32  }