Example usage for com.google.gson FieldNamingPolicy LOWER_CASE_WITH_UNDERSCORES

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

Introduction

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

Prototype

FieldNamingPolicy LOWER_CASE_WITH_UNDERSCORES

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

Click Source Link

Document

Using this naming policy with Gson will modify the Java Field name from its camel cased form to a lower case field name where each word is separated by an underscore (_).

Usage

From source file:qa.qcri.nadeef.core.datamodel.CleanPlan.java

License:Open Source License

/**
 * Creates a {@link CleanPlan} from JSON object.
 *
 * @param reader JSON string reader./*from   ww w  .j a va2  s  .  c o m*/
 * @param dbConfig Nadeef DB config.
 * @return instance.
 */
public static List<CleanPlan> create(Reader reader, DBConfig dbConfig) throws Exception {
    Preconditions.checkNotNull(reader);
    GsonBuilder gson = new GsonBuilder();
    gson.registerTypeAdapter(CleanPlanJsonAdapter.class, new CleanPlanJsonDeserializer());
    gson.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
    CleanPlanJsonAdapter adapter = gson.create().fromJson(reader, CleanPlanJsonAdapter.class);
    return create(adapter, dbConfig);
}

From source file:qa.qcri.nadeef.core.datamodel.CleanPlan.java

License:Open Source License

/**
 * Creates a {@link CleanPlan} from JSON object.
 *
 * @param json JSON object./* ww  w. j av  a2s  .  co m*/
 * @param dbConfig Nadeef DB config.
 * @return instance.
 */
public static List<CleanPlan> create(JsonObject json, DBConfig dbConfig) throws Exception {
    Preconditions.checkNotNull(json);
    GsonBuilder gson = new GsonBuilder();
    gson.registerTypeAdapter(CleanPlanJsonAdapter.class, new CleanPlanJsonDeserializer());
    gson.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
    CleanPlanJsonAdapter adapter = gson.create().fromJson(json, CleanPlanJsonAdapter.class);
    return create(adapter, dbConfig);
}

From source file:qa.qcri.qnoise.Qnoise.java

License:MIT License

public static void main(String[] args) {
    options = createQnoiseOption();/* w w w. ja va  2  s  . com*/
    CommandLineParser parser = new GnuParser();

    CSVReader reader = null;
    CSVWriter writer = null;
    try {
        CommandLine line = parser.parse(options, args);
        if (line.hasOption("v")) {
            Tracer.setVerbose(true);
        }

        final String inputFileName = line.getOptionValue("f");
        if (Files.notExists(Paths.get(inputFileName))) {
            throw new FileNotFoundException("Input file " + inputFileName + " does not exist.");
        }

        JsonReader jsonReader = new JsonReader(
                new InputStreamReader(new FileInputStream(inputFileName), Charset.forName("UTF-8")));

        GsonBuilder gson = new GsonBuilder();
        gson.registerTypeAdapter(NoiseJsonAdapter.class, new NoiseJsonAdapterDeserializer());
        gson.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
        NoiseJsonAdapter adapter = gson.create().fromJson(jsonReader, NoiseJsonAdapter.class);

        reader = new CSVReader(new FileReader(adapter.getInputFile()), adapter.getCsvSeparator());
        DataProfile profile = DataProfile.readData(reader, adapter.getSchema());

        final String outputFileName = line.getOptionValue("o");
        writer = new CSVWriter(new FileWriter(outputFileName), adapter.getCsvSeparator(),
                CSVWriter.NO_QUOTE_CHARACTER, CSVWriter.NO_ESCAPE_CHARACTER);

        QnoiseFacade.inject(profile, adapter.getSpecs(), new IAction<NoiseContext>() {
            @Override
            public void act(NoiseContext context, HashMap<String, Object> extras) {
                context.report.appendMetric(NoiseReport.Metric.InputFilePath, inputFileName);

                context.report.appendMetric(NoiseReport.Metric.OutputFilePath, outputFileName);
                context.report.saveToFile(context.spec.logFile);
                context.report.print();
            }
        });

        profile.writeData(writer);
    } catch (MissingOptionException me) {
        printHelp();
    } catch (ParseException ex) {
        ex.printStackTrace();
        printHelp();
    } catch (Exception ex) {
        tracer.println("Exception : " + ex.getMessage());
        ex.printStackTrace();
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }

            if (writer != null) {
                writer.close();
            }
        } catch (Exception ex) {
        }
    }
}

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 a v  a2 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:src.MainApp.java

/**
 * Constructor./* w ww  . jav a  2  s  . co  m*/
 */
public MainApp() {

    initUser();

    GsonBuilder builder = new GsonBuilder();
    builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
    builder.enableComplexMapKeySerialization();
    gson = FxGson.addFxSupport(builder).create();

    //setCurrUser(new Profile(new User("", "", "", 123, "", 0, 0, new DriversLicense("",0)),"test"));
    rideContainer = new RideOverview();
    //If file exists, load
    /**File ride = new File("src/main/resources/ridedata.json");
    File user = new File("src/main/resources/userdata.json");
    if (ride.exists() && user.exists())
    {
       try {
    currUser = load();
       } catch (UnsupportedEncodingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
       }
    } else {
       currUser = new Profile(new User("", ""));
       rideContainer = new RideOverview();
    }
    if (currUser == null){
       System.out.print(":(");
    } else {
       System.out.println(currUser.getUserRoutes());
    } */
}

From source file:tools.devnull.boteco.channel.telegram.converters.TelegramIncomeConverter.java

License:Open Source License

@Converter
public TelegramPolling convert(Map map) throws Exception {
    Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
    return gson.fromJson(gson.toJson(map), TelegramPolling.class);
}

From source file:travel.izi.sdk.util.GsonHelper.java

License:Apache License

/**
 * Create a {@link com.google.gson.GsonBuilder} and register all of the custom types needed in order to properly
 * deserialize complex IZITravel-specific type.
 *
 * @return Assembled GSON builder instance.
 *//*  w ww  .  j a v a 2 s .co m*/
public static GsonBuilder getGsonBuilder() {
    GsonBuilder builder = new GsonBuilder();

    builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
    builder.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");

    //enum types
    builder.registerTypeAdapter(Category.class, new JsonDeserializer<Category>() {
        @Override
        public Category deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            return Category.fromValue(json.getAsString());
        }
    });
    builder.registerTypeAdapter(MediaType.class, new JsonDeserializer<MediaType>() {
        @Override
        public MediaType deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            return MediaType.fromValue(json.getAsString());
        }
    });
    builder.registerTypeAdapter(MtgObjectType.class, new JsonDeserializer<MtgObjectType>() {
        @Override
        public MtgObjectType deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            return MtgObjectType.fromValue(json.getAsString());
        }
    });
    builder.registerTypeAdapter(Placement.class, new JsonDeserializer<Placement>() {
        @Override
        public Placement deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            return Placement.fromValue(json.getAsString());
        }
    });
    builder.registerTypeAdapter(PlaybackType.class, new JsonDeserializer<PlaybackType>() {
        @Override
        public PlaybackType deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            return PlaybackType.fromValue(json.getAsString());
        }
    });
    builder.registerTypeAdapter(Status.class, new JsonDeserializer<Status>() {
        @Override
        public Status deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            return Status.fromValue(json.getAsString());
        }
    });
    builder.registerTypeAdapter(TriggerZoneType.class, new JsonDeserializer<TriggerZoneType>() {
        @Override
        public TriggerZoneType deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            return TriggerZoneType.fromValue(json.getAsString());
        }
    });

    return builder;
}

From source file:us.socialgoodworking.mocklocation.MockLocationActivity.java

License:Apache License

public void saveRoutes() {
    final Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .create();//ww w. j a  v a 2 s . c o  m
    String json = gson.toJson(routeList);
    Logging.debug(TAG, "saveRoutes", json);
    IO.writeFile(getApplicationContext(), routeDir, routeFile, json, false);
}

From source file:us.socialgoodworking.mocklocation.MockLocationActivity.java

License:Apache License

public void readRoutes() {
    if (routeList == null)
        routeList = new Routes();

    String r = IO.readFile(getApplicationContext(), routeDir, routeFile);
    if (r.length() > 0) {
        Logging.debug(TAG, "readRoutes", r);
        final Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
                .create();//from  w w  w  .j av a 2 s. co  m
        routeList = gson.fromJson(r, Routes.class);
    }
}