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:io.realm.examples.realmgridview.GridViewExampleActivity.java

License:Apache License

private List<City> loadCities() {
    // In this case we're loading from local assets.
    // NOTE: could alternatively easily load from network
    InputStream stream = null;//from   ww w.j  av  a  2  s  .c om
    try {
        stream = getAssets().open("cities.json");
    } catch (IOException e) {
        return null;
    }

    // GSON can parse the data.
    // Note there is a bug in GSON 2.3.1 that can cause it to StackOverflow when working with RealmObjects.
    // To work around this, use the ExclusionStrategy below or downgrade to 1.7.1
    // See more here: https://code.google.com/p/google-gson/issues/detail?id=440
    Gson gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() {
        @Override
        public boolean shouldSkipField(FieldAttributes f) {
            return f.getDeclaringClass().equals(RealmObject.class);
        }

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

    JsonElement json = new JsonParser().parse(new InputStreamReader(stream));
    List<City> cities = gson.fromJson(json, new TypeToken<List<City>>() {
    }.getType());

    // Open a transaction to store items into the realm
    // Use copyToRealm() to convert the objects into proper RealmObjects managed by Realm.
    realm.beginTransaction();
    Collection<City> realmCities = realm.copyToRealm(cities);
    realm.commitTransaction();

    return new ArrayList<City>(realmCities);
}

From source file:io.realm.examples.realmrecyclerview.RecyclerViewExampleActivity.java

License:Apache License

private void initGson() {
    gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() {
        @Override/* w ww.j  a  v a  2s . c o m*/
        public boolean shouldSkipField(FieldAttributes f) {
            return f.getDeclaringClass().equals(RealmObject.class);
        }

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

From source file:io.vertigo.vega.rest.engine.GoogleJsonEngine.java

License:Apache License

private Gson createGson() {
    return new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").setPrettyPrinting()
            //TODO  registerTypeAdapter(String.class, new EmptyStringAsNull<>())// add "" <=> null
            //.serializeNulls()//On veut voir les null
            .registerTypeAdapter(UiObject.class, new UiObjectDeserializer<>())
            .registerTypeAdapter(UiListDelta.class, new UiListDeltaDeserializer<>())
            .registerTypeAdapter(UiList.class, new UiListDeserializer<>())
            //.registerTypeAdapter(UiObjectExtended.class, new UiObjectExtendedDeserializer<>())
            /*.registerTypeAdapter(DtObjectExtended.class, new JsonSerializer<DtObjectExtended<?>>() {
               @Override//from   ww  w .j a  va 2  s  . c  om
               public JsonElement serialize(final DtObjectExtended<?> src, final Type typeOfSrc, final JsonSerializationContext context) {
                  final JsonObject jsonObject = new JsonObject();
                  final JsonObject jsonInnerObject = (JsonObject) context.serialize(src.getInnerObject());
                  for (final Entry<String, JsonElement> entry : jsonInnerObject.entrySet()) {
                     jsonObject.add(entry.getKey(), entry.getValue());
                  }
                  for (final Entry<String, Serializable> entry : src.entrySet()) {
                     jsonObject.add(entry.getKey(), context.serialize(entry.getValue()));
                  }
                  return jsonObject;
               }
            })*/
            .registerTypeAdapter(FacetedQueryResult.class, new JsonSerializer<FacetedQueryResult>() {
                @Override
                public JsonElement serialize(final FacetedQueryResult facetedQueryResult, final Type typeOfSrc,
                        final JsonSerializationContext context) {
                    final JsonObject jsonObject = new JsonObject();
                    //1- add result list as data
                    final JsonArray jsonData = (JsonArray) context.serialize(facetedQueryResult.getDtList());
                    jsonObject.add("data", jsonData);

                    //2- add facet list as facets
                    final List<Facet> facets = facetedQueryResult.getFacets();
                    final JsonArray facetList = new JsonArray();
                    for (final Facet facet : facets) {
                        final JsonObject jsonFacet = new JsonObject();

                        final Map<String, Long> maps = new HashMap<>();
                        for (final Entry<FacetValue, Long> entry : facet.getFacetValues().entrySet()) {
                            maps.put(entry.getKey().getLabel().getDisplay(), entry.getValue());
                        }

                        final JsonObject jsonFacetValues = (JsonObject) context.serialize(maps);
                        final String facetName = facet.getDefinition().getLabel().getDisplay();
                        jsonFacet.add(facetName, jsonFacetValues);
                        facetList.add(jsonFacet);
                    }
                    jsonObject.add("facets", context.serialize(facetList));
                    return jsonObject;
                }
            }).registerTypeAdapter(ComponentInfo.class, new JsonSerializer<ComponentInfo>() {
                @Override
                public JsonElement serialize(final ComponentInfo componentInfo, final Type typeOfSrc,
                        final JsonSerializationContext context) {
                    final JsonObject jsonObject = new JsonObject();
                    jsonObject.add(componentInfo.getTitle(), context.serialize(componentInfo.getValue()));
                    return jsonObject;
                }
            }).registerTypeAdapter(List.class, new JsonSerializer<List>() {

                @Override
                public JsonElement serialize(final List src, final Type typeOfSrc,
                        final JsonSerializationContext context) {
                    if (src.isEmpty()) {
                        return null;
                    }
                    return context.serialize(src);
                }
            }).registerTypeAdapter(Map.class, new JsonSerializer<Map>() {

                @Override
                public JsonElement serialize(final Map src, final Type typeOfSrc,
                        final JsonSerializationContext context) {
                    if (src.isEmpty()) {
                        return null;
                    }
                    return context.serialize(src);
                }
            }).registerTypeAdapter(DefinitionReference.class, new JsonSerializer<DefinitionReference>() {

                @Override
                public JsonElement serialize(final DefinitionReference src, final Type typeOfSrc,
                        final JsonSerializationContext context) {
                    return context.serialize(src.get().getName());
                }
            }).registerTypeAdapter(Option.class, new JsonSerializer<Option>() {

                @Override
                public JsonElement serialize(final Option src, final Type typeOfSrc,
                        final JsonSerializationContext context) {
                    if (src.isDefined()) {
                        return context.serialize(src.get());
                    }
                    return null; //rien
                }
            }).registerTypeAdapter(Class.class, new JsonSerializer<Class>() {

                @Override
                public JsonElement serialize(final Class src, final Type typeOfSrc,
                        final JsonSerializationContext context) {
                    return new JsonPrimitive(src.getName());
                }
            }).addSerializationExclusionStrategy(new ExclusionStrategy() {
                @Override
                public boolean shouldSkipField(final FieldAttributes arg0) {
                    if (arg0.getAnnotation(JsonExclude.class) != null) {
                        return true;
                    }
                    return false;
                }

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

From source file:logic.DiskIOManager.java

License:Open Source License

public static void saveLibrary(MangaLibrary library, SavePart part) {
    try {//from   ww  w. j a v a  2s. c o  m
        String configDirectory = library.getConfigDirectory();
        File configDir = new File(configDirectory);
        if (!Files.exists(Paths.get(configDir.toURI())))
            configDir.mkdirs();

        assert library != null;
        Gson gson = new GsonBuilder().setPrettyPrinting().setExclusionStrategies(new ExclusionStrategy() {
            public boolean shouldSkipClass(Class<?> clazz) {
                return false;
            }

            public boolean shouldSkipField(FieldAttributes f) {
                return (f.getName().equals("configDirectory")) || (f.getName().equals("available"));
            }
        }).create();

        String generatedLibrary = gson.toJson(library, library.getClass());
        String generatedAvailable = gson.toJson(library.getAvailable(), library.getAvailable().getClass());

        if (part == SavePart.COLLECTIONS)
            saveLibraryPart(generatedLibrary, configDirectory, "library.json");
        if (part == SavePart.AVAILABLE)
            saveLibraryPart(generatedAvailable, configDirectory, "available.json");

    } catch (IOException e) {
        e.printStackTrace();
        M.print(e.getMessage());
    }
}

From source file:nars.io.JSONOutput.java

License:Open Source License

protected void init(boolean pretty) {
    GsonBuilder builder = new GsonBuilder().addSerializationExclusionStrategy(new ExclusionStrategy() {

        @Override//from   ww  w.j  av a2  s  . c o m
        public boolean shouldSkipField(FieldAttributes fa) {
            //System.out.println(fa.getDeclaredClass() + 
            //" " + fa.getName());
            if (fa.getName().equals("derivationChain")) {
                return true;
            }

            return false;
        }

        @Override
        public boolean shouldSkipClass(Class<?> type) {
            return false;
        }
    })
            //.registerTypeAdapter(Id.class, new IdTypeAdapter())
            //.setDateFormat(DateFormat.LONG)
            //.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
            //.setVersion(1.0)                
            .enableComplexMapKeySerialization().serializeNulls().disableHtmlEscaping();

    if (pretty) {
        builder.setPrettyPrinting();
    }
    gson = builder.create();

}

From source file:nars.util.JSONOutput.java

License:Open Source License

protected void init(boolean pretty) {
    GsonBuilder builder = new GsonBuilder().addSerializationExclusionStrategy(new ExclusionStrategy() {

        @Override//from   w  w w  .  j  a v  a  2 s  . c o m
        public boolean shouldSkipField(FieldAttributes fa) {
            return fa.getName().equals("derivationChain");
        }

        @Override
        public boolean shouldSkipClass(Class<?> type) {
            return false;
        }
    })
            //.registerTypeAdapter(Id.class, new IdTypeAdapter())
            //.setDateFormat(DateFormat.LONG)
            //.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
            //.setVersion(1.0)                
            .enableComplexMapKeySerialization().serializeNulls().disableHtmlEscaping();

    if (pretty) {
        builder.setPrettyPrinting();
    }
    gson = builder.create();

}

From source file:net.happybrackets.extras.assignment_autograding.BeadsChecker.java

License:Apache License

private void printCallChainJSON(UGen root, String filename) throws IOException {
    try (Writer writer = new OutputStreamWriter(new FileOutputStream(filename), "UTF-8")) {
        RuntimeTypeAdapterFactory<UGen> adapter = RuntimeTypeAdapterFactory //ouch that is hacky!
                .of(UGen.class).registerSubtype(Gain.class).registerSubtype(Glide.class)
                .registerSubtype(Noise.class).registerSubtype(Envelope.class).registerSubtype(WavePlayer.class)
                .registerSubtype(SamplePlayer.class).registerSubtype(GranularSamplePlayer.class)
                .registerSubtype(Clock.class).registerSubtype(TapOut.class).registerSubtype(BiquadFilter.class)
                .registerSubtype(Reverb.class).registerSubtype(Function.class).registerSubtype(Static.class)
                .registerSubtype(DelayTrigger.class).registerSubtype(TapIn.class)
                .registerSubtype(RecordToFile.class);

        Gson gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() {
            @Override/*from  w  ww  . j ava  2  s  . c  o  m*/
            public boolean shouldSkipClass(Class<?> clazz) { //more awful hackyness here!
                return (clazz == AudioContext.class || clazz == float[].class || clazz == RecordToFile.class
                        || clazz == TapIn.class || clazz == double[].class);
            }

            /**
             * Custom field exclusion goes here
             */
            @Override
            public boolean shouldSkipField(FieldAttributes f) {
                return false;
            }
        }).setPrettyPrinting().registerTypeAdapterFactory(adapter).create();
        gson.toJson(root, writer);
    }
}

From source file:ordo.servlet.api.APILieuxController.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w w  w. j  a v a 2 s .c om
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("application/json");

    JpaDepotDao daoDepot = JpaDepotDao.getInstance();
    JpaSwapLocationDao daoSwapLocation = JpaSwapLocationDao.getInstance();
    JpaCommandeClientDao daoCommandeClient = JpaCommandeClientDao.getInstance();

    Collection<Lieu> lieux = new ArrayList<>();
    lieux.addAll(daoDepot.findAll());
    lieux.addAll(daoSwapLocation.findAll());
    lieux.addAll(daoCommandeClient.findAll(false));

    if (lieux.isEmpty()) {
        CommandeClient c1 = new CommandeClient();
        Depot c2 = new Depot();
        c1.setId(1);
        c1.setQuantiteVoulue(26);
        c1.setCoordY(50.4291629f);
        c1.setCoordX(2.8278697f);
        c1.setLibelle("Sample Lieu");

        c2.setId(2);
        c2.setCoordY(50.5f);
        c2.setCoordX(2.8278697f);

        lieux.add(c1);
        lieux.add(c2);
    }

    String json = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() {
        @Override
        public boolean shouldSkipField(FieldAttributes f) {
            switch (f.getName()) {
            case "vehicule":
            case "colis":
                return true;
            }

            return false;
        }

        @Override
        public boolean shouldSkipClass(Class<?> clazz) {
            return false;
        }
    }).create().toJson(lieux);
    json = "{\"lieux\": " + json + "}";
    PrintWriter out = response.getWriter();
    out.print(json);
}

From source file:org.chaos.fx.cnbeta.net.CnBetaApiHelper.java

License:Apache License

public static void initialize() {
    sMobileApi = new Retrofit.Builder().baseUrl(MobileApi.BASE_URL).addConverterFactory(
            GsonConverterFactory.create(new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() {
                @Override/*from w  w  w.  ja v  a 2s.com*/
                public boolean shouldSkipField(FieldAttributes f) {
                    return f.getAnnotation(SerializedName.class) == null;
                }

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

    sMWebApi = new Retrofit.Builder().baseUrl(MWebApi.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create()).build().create(MWebApi.class);

    OkHttpClient okHttpClient = CnBetaHttpClientProvider.newCnBetaHttpClient();

    sWebApi = new Retrofit.Builder().baseUrl(WebApi.HOST_URL).client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create()).build().create(WebApi.class);

    sCookieDownloader = new OkHttp3Downloader(okHttpClient);
}

From source file:org.dspace.app.webui.discovery.DiscoveryJSONRequest.java

License:BSD License

private void doAutocomplete(Context context, HttpServletRequest request, HttpServletResponse resp) {
    try {/*w  w  w .  ja  v a2s.c  om*/
        DSpaceObject scope = DiscoverUtility.getSearchScope(context, request);
        DiscoverQuery autocompleteQuery = DiscoverUtility.getDiscoverAutocomplete(context, request, scope);
        DiscoverResult qResults = SearchUtils.getSearchService().search(context, autocompleteQuery);
        // extract the only facet present in the result response
        Set<String> facets = qResults.getFacetResults().keySet();
        List<FacetResult> fResults = new ArrayList<DiscoverResult.FacetResult>();
        if (facets != null && facets.size() > 0) {
            String autocompleteField = (String) facets.toArray()[0];
            fResults = qResults.getFacetResult(autocompleteField);
        }
        Gson gson = new GsonBuilder().addSerializationExclusionStrategy(new ExclusionStrategy() {

            @Override
            public boolean shouldSkipField(FieldAttributes f) {

                if (f.getName().equals("asFilterQuery"))
                    return true;
                return false;
            }

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

        JsonElement tree = gson.toJsonTree(fResults);
        JsonObject jo = new JsonObject();
        jo.add("autocomplete", tree);
        resp.getWriter().write(jo.toString());
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}