Example usage for com.google.gson ExclusionStrategy ExclusionStrategy

List of usage examples for com.google.gson ExclusionStrategy ExclusionStrategy

Introduction

In this page you can find the example usage for com.google.gson ExclusionStrategy ExclusionStrategy.

Prototype

ExclusionStrategy

Source Link

Usage

From source file:org.mitre.swd.view.SwdResponse.java

License:Apache License

@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response) {/*from w w w.j a  v a  2  s . co  m*/
    Gson gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() {

        @Override
        public boolean shouldSkipField(FieldAttributes f) {
            return false;
        }

        @Override
        public boolean shouldSkipClass(Class<?> clazz) {
            // skip the JPA binding wrapper
            if (clazz.equals(BeanPropertyBindingResult.class)) {
                return true;
            } else {
                return false;
            }
        }

    }).create();

    response.setContentType("application/json");

    Object obj = model.get("entity");
    if (obj == null) {
        obj = model;
    }

    Writer out;

    try {

        out = response.getWriter();
        gson.toJson(obj, out);

    } catch (IOException e) {

        logger.error("IOException in SwdResponse.java: ", e);

    }

}

From source file:org.mitre.swd.view.XrdJsonResponse.java

License:Apache License

@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response) {//from w  w w. j a v  a 2 s.co  m
    Gson gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() {

        @Override
        public boolean shouldSkipField(FieldAttributes f) {
            return false;
        }

        @Override
        public boolean shouldSkipClass(Class<?> clazz) {
            // skip the JPA binding wrapper
            if (clazz.equals(BeanPropertyBindingResult.class)) {
                return true;
            } else {
                return false;
            }
        }

    }).create();

    response.setContentType("application/json");

    Map<String, String> links = (Map<String, String>) model.get("links");

    JsonObject obj = new JsonObject();
    JsonArray linksList = new JsonArray();
    obj.add("links", linksList);

    // map of "rel" -> "link" values
    for (Map.Entry<String, String> link : links.entrySet()) {
        JsonObject l = new JsonObject();
        l.addProperty("rel", link.getKey());
        l.addProperty("link", link.getValue());

        linksList.add(l);
    }

    Writer out;

    try {

        out = response.getWriter();
        gson.toJson(obj, out);

    } catch (IOException e) {

        logger.error("IOException in XrdJsonResponse.java: ", e);

    }
}

From source file:org.netxms.websvc.json.JsonTools.java

License:Open Source License

/**
 * Create JSON representation for given object
 * //from w w w.  jav a  2s.c o m
 * @param object object to serialize
 * @return JSON code
 */
public static String jsonFromObject(Object object) {
    if (object instanceof JsonObject)
        return ((JsonObject) object).toString();
    if (object instanceof ResponseContainer)
        return ((ResponseContainer) object).toJson();

    GsonBuilder builder = new GsonBuilder();
    builder.setPrettyPrinting(); // FIXME: remove for production
    builder.registerTypeAdapter(Date.class, new DateAdapter());
    builder.registerTypeAdapter(InetAddress.class, new InetAddressAdapter());
    builder.registerTypeAdapter(InetAddressEx.class, new InetAddressExAdapter());
    builder.registerTypeAdapter(MacAddress.class, new MacAddressAdapter());
    builder.setExclusionStrategies(new ExclusionStrategy() {
        @Override
        public boolean shouldSkipField(FieldAttributes f) {
            return f.getAnnotation(Internal.class) != null;
        }

        @Override
        public boolean shouldSkipClass(Class<?> c) {
            return c.isAnnotationPresent(Internal.class);
        }
    });
    return builder.create().toJson(object);
}

From source file:org.opendaylight.tsdr.persistence.elasticsearch.ElasticsearchStore.java

License:Open Source License

/**
 * Built a client configuration also base on properties file.
 *//* w w  w.  j  a  va 2s. c o  m*/
private HttpClientConfig buildClientConfig() throws IOException {
    GsonBuilder gson = new GsonBuilder().setFieldNamingStrategy(field -> {
        String name = FieldNamingPolicy.UPPER_CAMEL_CASE.translateName(field);
        if (name.startsWith("_")) {
            return name.substring(1);
        }
        return name;
    }).setExclusionStrategies(new ExclusionStrategy() {
        @Override
        public boolean shouldSkipField(FieldAttributes fieldAttributes) {
            String name = fieldAttributes.getName().toLowerCase();
            return name.equals("hash") || name.equals("hashvalid");
        }

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

    String serverUrl = properties.get("serverUrl");
    HttpClientConfig.Builder configBuilder = new HttpClientConfig.Builder(serverUrl).multiThreaded(true)
            .gson(gson.create());

    if (Boolean.valueOf(properties.get("nodeDiscovery"))) {
        configBuilder.discoveryEnabled(true).discoveryFrequency(1L, TimeUnit.MINUTES);
    }

    String username = properties.get("username");
    String password = properties.get("password");
    if (!Strings.isNullOrEmpty(username) && !Strings.isNullOrEmpty(password)) {
        configBuilder.defaultCredentials(username, password);
    }

    return configBuilder.build();
}

From source file:ru.payqr.dadataexample.rest.DaDataRestClient.java

License:Open Source License

private DaDataRestClient() {
    Gson gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() {
        @Override//from  w w  w .  j a  v  a 2s .co  m
        public boolean shouldSkipField(FieldAttributes f) {
            return f.getDeclaringClass().equals(RealmObject.class);
        }

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

    RestAdapter restAdapter = new RestAdapter.Builder()
            .setLogLevel(BuildConfig.DEBUG ? RestAdapter.LogLevel.FULL : RestAdapter.LogLevel.NONE)
            .setEndpoint(BASE_URL).setRequestInterceptor(new RequestInterceptor() {
                @Override
                public void intercept(RequestFacade request) {
                    request.addHeader("Content-Type", "application/json");
                    request.addHeader("Accept", "application/json");
                    request.addHeader("Authorization", "Token ".concat(BuildConfig.DADATA_API_KEY));
                }
            }).setConverter(new GsonConverter(gson)).build();

    apiService = restAdapter.create(DaDataService.class);
}

From source file:ru.payqr.kladapiexample.rest.KladrRestClient.java

License:Open Source License

private KladrRestClient() {
    Gson gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() {
        @Override/*from  w  w  w  . ja  va2  s . c  o m*/
        public boolean shouldSkipField(FieldAttributes f) {
            return f.getDeclaringClass().equals(RealmObject.class);
        }

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

    RestAdapter restAdapter = new RestAdapter.Builder()
            .setLogLevel(BuildConfig.DEBUG ? RestAdapter.LogLevel.FULL : RestAdapter.LogLevel.NONE)
            .setEndpoint(BASE_URL).setRequestInterceptor(new RequestInterceptor() {
                @Override
                public void intercept(RequestFacade request) {
                    request.addQueryParam("token", BuildConfig.KLADR_TOKEN_KEY);
                    request.addQueryParam("key", BuildConfig.KLADR_API_KEY);
                }
            }).setConverter(new GsonConverter(gson)).build();

    apiService = restAdapter.create(KladrService.class);
}

From source file:se.liu.imt.mi.eee.validation.json.AOMtoJSONandYAMLSerializer.java

License:LGPL

/**
 * Create an outputter with default encoding, indent and lineSeparator
 * TODO: fix node_i_d --> node_id//w w  w .j av  a  2  s .co  m
 */
public AOMtoJSONandYAMLSerializer() {
    this.encoding = UTF8;
    this.indent = "    "; // 4 white space characters
    this.lineSeparator = "\r\n";

    gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .setExclusionStrategies(new ExclusionStrategy() {
                public boolean shouldSkipClass(Class<?> clazz) {
                    if (clazz == Archetype.class)
                        return true; // Avoid circular reference
                    return false;
                }

                /* Custom field exclusion goes here */
                public boolean shouldSkipField(FieldAttributes f) {
                    //System.out.println("---> "+f.getName());
                    if (f.getName().equalsIgnoreCase("termDefinitionMap"))
                        return true;
                    if (f.getName().equalsIgnoreCase("constraintDefinitionMap"))
                        return true;
                    if (f.getName().equalsIgnoreCase("hiddenOnForm"))
                        return true;
                    if (f.getName().equalsIgnoreCase("existence"))
                        return true;

                    if (f.getName().equalsIgnoreCase("existence")) {
                        System.out.println(" ==> " + f.getDeclaredClass().getCanonicalName());
                    }
                    //                  System.out.println(f.getDeclaredClass());
                    //                  return (f.getName().equalsIgnoreCase("code") && f.getDeclaredClass().equals(ArchetypeTerm.class));
                    //return (f.getName().equalsIgnoreCase("code")); //TODO: check that no other fields named "code" are there
                    return false;
                }
            }).registerTypeAdapter(CodePhrase.class, new CodePhraseConverter())
            .registerTypeAdapter(DvDateTime.class, new DvDateTimeConverter())
            .registerTypeAdapter(Interval.class, new IntervalConverterSequenceFormat())
            //.setDateFormat("yyyy-MM-dd'T'HH:mm:ss") // TODO: Check what to do with timezones (probably yoda stuff if DvDateTimeConverter does not suffice)
            .create();

    DumperOptions dumperOptions = new DumperOptions();
    //dumperOptions.setDefaultFlowStyle(FlowStyle.BLOCK);
    //dumperOptions.setLineBreak(LineBreak.WIN);
    dumperOptions.setWidth(120);
    //dumperOptions.setDefaultFlowStyle(FlowStyle.FLOW);
    //dumperOptions.setPrettyFlow(true);
    //dumperOptions.setDefaultScalarStyle(ScalarStyle.DOUBLE_QUOTED);           
    yaml = new Yaml(dumperOptions); // Yaml(new SyntaxSugarRepresenter());
    //yaml.setBeanAccess(BeanAccess.PROPERTY);

}

From source file:uk.ac.horizon.aestheticodes.server.ExperienceParser.java

License:Open Source License

public static Gson createParser() {
    GsonBuilder build = new GsonBuilder();
    build.registerTypeAdapter(new TypeToken<Map<String, Marker>>() {
    }.getType(), new MarkerMapAdapter());
    build.addSerializationExclusionStrategy(new ExclusionStrategy() {
        @Override/* w w  w. j a  v  a 2  s .  co m*/
        public boolean shouldSkipField(FieldAttributes f) {
            final JsonIgnore ignore = f.getAnnotation(JsonIgnore.class);
            return ignore != null;
        }

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

From source file:util.PodbaseUtil.java

License:MIT License

public static Gson getGsonExcludesGsonTransient() {
    Gson gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() {
        @Override/*from w  ww  .ja v a2  s  .  c o m*/
        public boolean shouldSkipClass(Class<?> arg0) {
            return false;
        }

        @Override
        public boolean shouldSkipField(FieldAttributes field) {
            GsonTransient annotation = field.getAnnotation(GsonTransient.class);
            return annotation != null;
        }
    }).registerTypeAdapter(ImageAttribute.class, new ImageAttributeAdaptor())
            .registerTypeAdapter(AccessType.class, new AccessTypeAdaptor())
            .registerTypeAdapter(VirtualAccessType.class, new VirtualAccessTypeAdaptor())
            .registerTypeAdapter(Activation.class, new ActivationAdaptor())
            .registerTypeAdapter(Date.class, new DateAdaptor()).create();
    return gson;
}