Example usage for com.google.gson FieldNamingPolicy IDENTITY

List of usage examples for com.google.gson FieldNamingPolicy IDENTITY

Introduction

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

Prototype

FieldNamingPolicy IDENTITY

To view the source code for com.google.gson FieldNamingPolicy IDENTITY.

Click Source Link

Document

Using this naming policy with Gson will ensure that the field name is unchanged.

Usage

From source file:api.PersonResource.java

public PersonResource() {
    gson = new GsonBuilder().setPrettyPrinting().setFieldNamingPolicy(FieldNamingPolicy.IDENTITY).create();
}

From source file:ca.oson.json.Oson.java

License:Open Source License

public Gson getGson() {
    if (gson == null) {
        GsonBuilder gsonBuilder = new GsonBuilder();

        switch (getDefaultType()) {
        case ALWAYS:
            gsonBuilder.serializeNulls();
            break;
        case NON_NULL:
            break;
        case NON_EMPTY:
            break;
        case DEFAULT:
            gsonBuilder.serializeNulls();
            break;
        default:/*from w w w . j  a va2 s .  c o  m*/
            gsonBuilder.serializeNulls();
            break;
        }

        switch (getFieldNaming()) {
        case FIELD: // original field name: someField_name
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.IDENTITY);
            break;
        case LOWER: // somefield_name -> some_field_name
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
            break;
        case UPPER: //SOMEFIELD_NAME -> SomeFieldName
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE);
            break;
        case CAMELCASE: // someFieldName
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.IDENTITY);
            break;
        case UPPER_CAMELCASE: // SomeFieldName
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE);
            break;
        case UNDERSCORE_CAMELCASE: // some_Field_Name
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
            break;
        case UNDERSCORE_UPPER_CAMELCASE: // Some_Field_Name
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
            break;
        case UNDERSCORE_LOWER: // some_field_name
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
            break;
        case UNDERSCORE_UPPER: // SOME_FIELD_NAME
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
            break;
        case SPACE_CAMELCASE: // some Field Name
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES);
            break;
        case SPACE_UPPER_CAMELCASE: // Some Field Name
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES);
            break;
        case SPACE_LOWER: // some field name
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES);
            break;
        case SPACE_UPPER: // SOME FIELD NAME
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES);
            break;
        case DASH_CAMELCASE: // some-Field-Name
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES);
            break;
        case DASH_UPPER_CAMELCASE: // Some-Field-Name
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES);
            break;
        case DASH_LOWER: // some-field-name
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES);
            break;
        case DASH_UPPER: // SOME-FIELD-NAME
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES);
            break;
        default:
            gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.IDENTITY);
            break;
        }

        if (getPrettyPrinting() && getIndentation() > 0) {
            gsonBuilder.setPrettyPrinting();
        }

        gsonBuilder.setDateFormat(options.getSimpleDateFormat());

        Set<FieldMapper> mappers = getFieldMappers();
        Map<Class, ClassMapper> classMappers = getClassMappers();
        List<ExclusionStrategy> strategies = new ArrayList<>();
        if (mappers != null) {
            gsonBuilder.setFieldNamingStrategy(new FieldNamingStrategy() {
                @Override
                public String translateName(Field f) {
                    String fieldName = f.getName();
                    String serializedName = java2Json(f);
                    if (!fieldName.equalsIgnoreCase(serializedName)) {
                        // if null returned, this field is ignored
                        return serializedName;
                    }
                    return json2Java(f);
                }
            });

            for (FieldMapper mapper : mappers) {
                if (mapper.java == null || mapper.json == null || mapper.ignore) {
                    strategies.add(new ExclusionStrategy() {

                        @Override
                        public boolean shouldSkipField(FieldAttributes f) {
                            String name = f.getName();
                            Class cls = f.getClass();

                            if (mapper.java == null) {
                                if (mapper.json.equals(name)) {
                                    if (mapper.getType() == null || cls.equals(mapper.getType())) {
                                        return true;
                                    }
                                }

                            } else if (mapper.json == null || mapper.ignore) {
                                if (mapper.java.equals(name)) {
                                    if (mapper.getType() == null || cls.equals(mapper.getType())) {
                                        return true;
                                    }
                                }

                            }

                            return false;
                        }

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

        if (classMappers != null) {
            for (Entry<Class, ClassMapper> entry : classMappers.entrySet()) {
                ClassMapper mapper = entry.getValue();
                if (mapper.getType() == null) {
                    mapper.setType(entry.getKey());
                }
                if (mapper.ignore != null && mapper.ignore) {
                    strategies.add(new ExclusionStrategy() {

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

                        @Override
                        public boolean shouldSkipClass(Class<?> clazz) {
                            if (clazz.equals(mapper.getType())) {
                                return true;
                            }
                            return false;
                        }
                    });
                }
            }

            for (Entry<Class, ClassMapper> entry : classMappers.entrySet()) {
                ClassMapper mapper = entry.getValue();
                if (!mapper.ignore && mapper.constructor != null) {
                    gsonBuilder.registerTypeAdapter(entry.getKey(), mapper.constructor);
                }
            }
        }

        int size = strategies.size();
        if (size > 0) {
            gsonBuilder.setExclusionStrategies(strategies.toArray(new ExclusionStrategy[size]));
        }

        Double version = getVersion();
        if (version != null) {
            gsonBuilder.setVersion(version);
        }

        if (isUseGsonExpose()) {
            gsonBuilder.excludeFieldsWithoutExposeAnnotation();
        }

        if (!DefaultValue.isDefault(getPatterns())) {
            gsonBuilder.setLenient();
        }

        gson = gsonBuilder.create();
    }

    return gson;
}

From source file:com.aliakseipilko.flightdutytracker.presenter.impl.CreateFlightPresenter.java

License:Open Source License

public CreateFlightPresenter(CreateFlightFragment view) {
    this.view = view;
    repository = new FlightRepository();
    //This should be injected with Dagger, but its retarded
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.IDENTITY);
    codeConverter = new AirportCodeConverter(view.getContext().getApplicationContext(), gsonBuilder.create());
}

From source file:com.aliakseipilko.flightdutytracker.presenter.impl.EditFlightPresenter.java

License:Open Source License

public EditFlightPresenter(EditFlightFragment view) {
    this.view = view;
    repository = new FlightRepository();
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.IDENTITY);
    codeConverter = new AirportCodeConverter(view.getContext().getApplicationContext(), gsonBuilder.create());
}

From source file:com.aliakseipilko.flightdutytracker.utils.BackupUtils.java

License:Open Source License

public static File serialiseFlightsRealmToFile(File destFile, RealmResults<Flight> data) throws IOException {
    destFile.createNewFile();//from  w w w . j a va  2 s  .c o  m
    destFile.setWritable(true);
    if (!destFile.canWrite()) {
        return null;
    }

    GsonBuilder gsonBuilder = new GsonBuilder();
    Gson gson = gsonBuilder.registerTypeAdapter(Flight.class, new FlightSerialiser()).serializeNulls()
            .setPrettyPrinting().setFieldNamingPolicy(FieldNamingPolicy.IDENTITY)
            .setDateFormat(DateFormat.FULL, DateFormat.FULL).create();

    JsonWriter writer = gson.newJsonWriter(new FileWriter(destFile));

    writer.beginArray();
    for (Flight f : data) {
        //            writer.beginArray();
        gson.toJson(f, Flight.class, writer);
        //            String json = gson.toJson(f, Flight.class);
        //            writer.endArray();
    }
    writer.endArray();
    writer.close();

    return destFile;
}

From source file:com.aliakseipilko.flightdutytracker.utils.BackupUtils.java

License:Open Source License

public static void deserialiseFlightsFileToRealm(Realm realm, final File srcFile,
        final BackupRestoreBaseFragment callingView) {

    realm.executeTransactionAsync(new Realm.Transaction() {
        @Override//from   w  w  w . j  a  va  2  s  .  c o m
        public void execute(Realm realm) {
            try {
                GsonBuilder gsonBuilder = new GsonBuilder();
                Gson gson = gsonBuilder.registerTypeAdapter(Flight.class, new FlightSerialiser())
                        .serializeNulls().setPrettyPrinting().setFieldNamingPolicy(FieldNamingPolicy.IDENTITY)
                        .setDateFormat(DateFormat.FULL, DateFormat.FULL).create();
                JsonReader reader = gson.newJsonReader(new FileReader(srcFile));
                List<Flight> flights;
                Type type = new TypeToken<List<Flight>>() {
                }.getType();

                flights = gson.fromJson(reader, type);

                for (Flight f : flights) {
                    //Check for ID duplication
                    if (realm.where(Flight.class).equalTo("id", f.getId()).findFirst() == null) {
                        realm.copyToRealm(f);
                    } else {
                        long newId;
                        Number idNum = realm.where(Flight.class).max("id");
                        if (idNum == null) {
                            newId = 1;
                        } else {
                            long id = idNum.longValue();
                            newId = id + 1;
                        }
                        f.setId(newId);
                        realm.copyToRealm(f);
                    }
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }, new Realm.Transaction.OnSuccess() {
        @Override
        public void onSuccess() {
            callingView.showSuccess("Restore completed successfully!");
        }
    }, new Realm.Transaction.OnError() {
        @Override
        public void onError(Throwable error) {
            callingView.showError("That didn't work. Try again");
        }
    });
}

From source file:com.gilecode.yagson.YaGson.java

License:Apache License

/**
 * Constructs a Gson object with the default configuration. The default configuration has the
 * following settings://from www  .  ja  va  2 s .  c  o m
 * <ul>
 *   <li>By default, YaGson's detects all self-references and the duplicate objects in the whole references graph
 *   of the serialized object. All such objects except the first one are emitted as link-like references, see
 *   {@link ReferencesPolicy#DUPLICATE_OBJECTS}. Although this policy may be changed to the alternative ones by
 *   {@link YaGsonBuilder#setReferencesPolicy(ReferencesPolicy)}, it is not recommended in case of arbitrary objects,
 *   as the functionality of the deserialized objects may be broken.</li>
 *   <li>By default, the type information is emitted as {@literal @type/@value} wrappers when the actual types
 *   would be lost otherwise, i.e. when the known de-serialization type is less specific than the actual class
 *   of an object or its part being serialized. Use
 *   {@link YaGsonBuilder#setTypeInfoPolicy(TypeInfoPolicy)} to change it if necessary.</li>
 *   <li>The JSON generated by <code>toJson</code> methods is in compact representation. This
 *   means that all the unneeded white-space is removed. You can change this behavior with
 *   {@link GsonBuilder#setPrettyPrinting()}. </li>
 *   <li>The generated JSON omits all the fields that are null. Note that nulls in arrays are
 *   kept as is since an array is an ordered list. Moreover, if a field is not null, but its
 *   generated JSON is empty, the field is kept. You can configure Gson to serialize null values
 *   by setting {@link GsonBuilder#serializeNulls()}.</li>
 *   <li>The default Date format is same as {@link java.text.DateFormat#DEFAULT}. This format
 *   ignores the millisecond portion of the date during serialization. You can change
 *   this by invoking {@link GsonBuilder#setDateFormat(int)} or
 *   {@link GsonBuilder#setDateFormat(String)}. </li>
 *   <li>By default, Gson ignores the {@link com.google.gson.annotations.Expose} annotation.
 *   You can enable Gson to serialize/deserialize only those fields marked with this annotation
 *   through {@link GsonBuilder#excludeFieldsWithoutExposeAnnotation()}. </li>
 *   <li>By default, Gson ignores the {@link com.google.gson.annotations.Since} annotation. You
 *   can enable Gson to use this annotation through {@link GsonBuilder#setVersion(double)}.</li>
 *   <li>The default field naming policy for the output Json is same as in Java. So, a Java class
 *   field <code>versionNumber</code> will be output as <code>&quot;versionNumber&quot;</code> in
 *   Json. The same rules are applied for mapping incoming Json to the Java classes. You can
 *   change this policy through {@link GsonBuilder#setFieldNamingPolicy(FieldNamingPolicy)}.</li>
 *   <li>By default, YaGson excludes <code>static</code> fields from
 *   consideration for serialization and deserialization, but serializes most of <code>transient</code>
 *   fields.
 *   You can change this behavior through
 *   {@link GsonBuilder#excludeFieldsWithModifiers(int...)}.</li>
 * </ul>
 */
public YaGson() {
    super(Excluder.DEFAULT.forReferencesPolicy(References.defaultPolicy()), FieldNamingPolicy.IDENTITY,
            Collections.<Type, InstanceCreator<?>>emptyMap(), false, TypeInfoPolicy.defaultPolicy().isEnabled(),
            DEFAULT_JSON_NON_EXECUTABLE, !TypeInfoPolicy.defaultPolicy().isEnabled(), // disable htmlSafe if types are printed
            false, false, LongSerializationPolicy.DEFAULT, Collections.<TypeAdapterFactory>emptyList(),
            References.defaultPolicy(), TypeInfoPolicy.defaultPolicy());
}

From source file:com.google.maps.TimeZoneApi.java

License:Open Source License

/**
 * Retrieve the {@link java.util.TimeZone} for the given location.
 *//*from  ww  w  .j  av  a 2s .co m*/
public static PendingResult<TimeZone> getTimeZone(GeoApiContext context, LatLng location) {
    return context.get(Response.class, FieldNamingPolicy.IDENTITY, BASE, "location", location.toString(),
            // Java has its own lookup for time -> DST, so we really only need to fetch the TZ id.
            // "timestamp" is, in effect, ignored.
            "timestamp", "0");
}

From source file:com.sangupta.clitools.finance.Currency.java

License:Apache License

@Override
public void run() {
    if (AssertUtils.isEmpty(arguments) || arguments.size() != 2) {
        System.out.println("Two 3-letter currency codes required!");
        return;// w  w w.  j a  v  a2s. co m
    }

    String curr1 = arguments.get(0).toUpperCase();
    String curr2 = arguments.get(1).toUpperCase();

    String url = "http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json";
    WebResponse response = WebInvoker.getResponse(url);
    if (response == null) {
        System.out.println("Unable to connect to internet to fetch currency rates!");
        return;
    }

    if (!response.isSuccess()) {
        System.out.println("Invalid server response!");
        return;
    }

    YahooResponse yr = GsonUtils.getGson(FieldNamingPolicy.IDENTITY).fromJson(response.getContent(),
            YahooResponse.class);
    if (yr == null) {
        System.out.println("Unable to decipher server response!");
        return;
    }

    String curr = curr1 + "/" + curr2;
    for (Resource resource : yr.list.resources) {
        if (curr.equals(resource.resource.fields.name)) {
            System.out.println("Name: " + curr);
            System.out.println("Rate: " + resource.resource.fields.price);
            System.out.println("Timestamp: " + resource.resource.fields.ts);
            long millis = StringUtils.getLongValue(resource.resource.fields.ts, 0) * 1000l;
            if (millis > 0) {
                System.out.println("Time: " + new Date(millis).toString());
            }

            return;
        }
    }
}

From source file:com.sangupta.jerry.mongodb.MongoDBUtils.java

License:Apache License

/**
 * Returns the MongoDB statistics for the given database.
 * /*from  ww w. ja  v  a  2s  .c  om*/
 * @param mongoDatabase
 * 
 * @return
 * 
 * @throws NullPointerException if database instance provided is <code>null</code>.
 */
public static MongoDBStats getDatabaseStatistics(DB mongoDatabase) {
    CommandResult commandResult = mongoDatabase.getStats();
    MongoDBStats stats = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.IDENTITY).create()
            .fromJson(commandResult.toString(), MongoDBStats.class);
    return stats;
}