Example usage for com.google.gson FieldNamingPolicy UPPER_CAMEL_CASE

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

Introduction

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

Prototype

FieldNamingPolicy UPPER_CAMEL_CASE

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

Click Source Link

Document

Using this naming policy with Gson will ensure that the first "letter" of the Java field name is capitalized when serialized to its JSON form.

Usage

From source file:agrold.webservices.GsonMessageBodyHandler.java

private Gson getGson() {
    if (gson == null) {
        final GsonBuilder gsonBuilder = new GsonBuilder();
        gson = gsonBuilder.disableHtmlEscaping().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
                .setPrettyPrinting().serializeNulls().create();
    }/*from w w w.  j a  v a2 s.co m*/
    return gson;
}

From source file:be.uantwerpen.dc.studyassistant.StudyAssistant.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  w  ww . j a va 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("text/html;charset=UTF-8");

    String urlPath = request.getServletPath();

    if (urlPath.equalsIgnoreCase("/resources")) {

        ArrayList<Environment> lcs = this.getEnvironmentResources();

        Integer min = Integer.MAX_VALUE;
        Integer max = Integer.MIN_VALUE;
        for (Environment e : lcs) {
            if (e.getArduinoloudness() != null && e.getArduinoloudness() < min) {
                min = e.getArduinoloudness();
            }
            if (e.getArduinoloudness() != null && e.getArduinoloudness() > max) {
                max = e.getArduinoloudness();
            }
        }

        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet StudyAssistant</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet StudyAssistant at " + request.getContextPath() + "</h1>");
            for (Environment e : lcs) {
                out.println(e.toString());
            }

            out.println("Noise MAX: " + max);
            out.println("Noise MIN: " + min);

            out.println("</body>");
            out.println("</html>");
        }
    } else if (urlPath.equalsIgnoreCase("/resources/gauge")) {
        Environment lastRecord = this.getLastEnvironmentRecord();

        StudyIndex inx = new StudyIndex(lastRecord);
        double index = inx.getStudyIndex();
        index *= 100;

        index = Math.round(index * 100.0) / 100.0;

        JsonObject obj = new JsonObject();

        // create an array called cols
        JsonArray cols = new JsonArray();
        JsonArray rows = new JsonArray();
        JsonArray messages = new JsonArray();

        JsonObject col = new JsonObject();
        col.addProperty("id", "Index");
        col.addProperty("label", "Index");
        col.addProperty("type", "string");
        cols.add(col);

        JsonObject col2 = new JsonObject();
        col2.addProperty("id", "Value");
        col2.addProperty("label", "Value");
        col2.addProperty("type", "number");
        cols.add(col2);

        obj.add("cols", cols);

        JsonObject c = new JsonObject();
        JsonArray row = new JsonArray();

        JsonObject v1 = new JsonObject();
        v1.addProperty("v", "Index");
        row.add(v1);

        JsonObject v2 = new JsonObject();
        v2.addProperty("v", index);
        row.add(v2);

        c.add("c", row);

        rows.add(c);

        obj.add("rows", rows);

        String msg = "";
        if ((inx.alcoholIndex < 0.90) || (inx.methaneIndex < 0.90)) {
            msg += "Room needs better air circulation.";
            JsonObject msg1 = new JsonObject();
            msg1.addProperty("text", msg);
            messages.add(msg1);
        }

        JsonObject msg2 = new JsonObject();
        msg = "";
        if (lastRecord.getArduinolight() < StudyIndex.lightOptimalValue) {
            msg += "Increase room luminance!";
        } else if (lastRecord.getArduinolight() > StudyIndex.lightOptimalValue) {
            msg += "Lower room luminance!";
        } else {
            msg += "Room luminance is optimal!";
        }
        msg2.addProperty("text", msg);
        messages.add(msg2);

        JsonObject msg3 = new JsonObject();
        msg = "";
        if (lastRecord.getDs18b20temp() < StudyIndex.temperatureOptimalValue) {
            msg += "Increase room temperature!";
        } else if (lastRecord.getDs18b20temp() > StudyIndex.temperatureOptimalValue) {
            msg += "Lower room temperature!";
        } else {
            msg += "Room temperature is optimal!";
        }
        msg3.addProperty("text", msg);
        messages.add(msg3);

        JsonObject msg4 = new JsonObject();
        msg = "";
        if (lastRecord.getArduinoloudness() > StudyIndex.loudnessOptimalValue) {
            msg += "Room is too noisy!";
            msg4.addProperty("text", msg);
            messages.add(msg4);
        }

        JsonObject msg5 = new JsonObject();
        msg = "";
        if (lastRecord.getDs18b20temp() < StudyIndex.temperatureOptimalValue) {
            msg += "Humidity is less than optimal.";
        } else if (lastRecord.getDs18b20temp() > StudyIndex.temperatureOptimalValue) {
            msg += "Humidity is above optimal.";
        } else {
            msg += "Humidity is optimal!";
        }
        msg5.addProperty("text", msg);
        messages.add(msg5);

        obj.add("messages", messages);

        Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls()
                .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();

        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");

        PrintWriter out = response.getWriter();

        out.print(gson.toJson(obj));
    } else if (urlPath.equalsIgnoreCase("/resources/humidity")) {
        JsonObject obj = this.getCoreChartsJson("Humidity");
        this.printJson(obj, response);
    } else if (urlPath.equalsIgnoreCase("/resources/temperature")) {
        JsonObject obj = this.getCoreChartsJson("Temperature");
        this.printJson(obj, response);
    } else if (urlPath.equalsIgnoreCase("/resources/loudness")) {
        JsonObject obj = this.getCoreChartsJson("Loudness");
        this.printJson(obj, response);
    } else if (urlPath.equalsIgnoreCase("/resources/light")) {
        JsonObject obj = this.getCoreChartsJson("Light");
        this.printJson(obj, response);
    } else if (urlPath.equalsIgnoreCase("/resources/bubbleindex")) {
        JsonObject obj = this.getCoreChartsJson("Environment Index Score");
        this.printJson(obj, response);
    } else if (urlPath.equalsIgnoreCase("/resources/minmax")) {
        JsonObject obj = this.findMinMax();
        this.printJson(obj, response);
    }
}

From source file:be.uantwerpen.dc.studyassistant.StudyAssistant.java

private void printJson(JsonObject obj, HttpServletResponse response) throws IOException {
    Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls()
            .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
            .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").create();

    response.setContentType("application/json");
    response.setCharacterEncoding("utf-8");

    PrintWriter out = response.getWriter();

    out.print(gson.toJson(obj));/*ww w  . j  av  a2 s .c  o  m*/
}

From source file:bisq.common.util.Utilities.java

License:Open Source License

public static <T> T jsonToObject(String jsonString, Class<T> classOfT) {
    Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).setPrettyPrinting()
            .create();//from   w  w w  .j av a 2 s .  co m
    return gson.fromJson(jsonString, classOfT);
}

From source file:br.com.tamarozzi.dao.impl.UsuarioDaoImpl.java

public UsuarioDaoImpl() {
    this.gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).setPrettyPrinting()
            .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:// w  w  w. ja v a2 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:cc.kave.commons.utils.json.JsonUtils.java

License:Apache License

private static GsonBuilder createBuilder() {
    GsonBuilder gb = new GsonBuilder();

    // add support for new Java 8 date/time framework
    gb.registerTypeHierarchyAdapter(LocalDateTime.class, new LocalDateTimeConverter());
    Converters.registerAll(gb);//from  ww w . jav  a 2 s .c  o  m
    gb.registerTypeAdapter(Duration.class, new DurationConverter());

    GsonUtil.addTypeAdapters(gb);

    registerNames(gb);
    registerSSTHierarchy(gb);
    registerEventHierarchy(gb);

    gb.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE);
    gb.excludeFieldsWithModifiers(java.lang.reflect.Modifier.TRANSIENT);

    return gb;
}

From source file:com.aliakseipilko.flightdutytracker.dagger.modules.GsonModule.java

License:Open Source License

@Provides
public Gson provideGson() {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE);
    return gsonBuilder.create();
}

From source file:com.amazonaws.reactnative.dynamodb.AWSRNDynamoDBClient.java

License:Open Source License

@ReactMethod
public void initWithOptions(final ReadableMap options) {
    if (!options.hasKey("region")) {
        throw new IllegalArgumentException("expected region key");
    }//from  w w w.java 2s .  c  o m
    final AWSRNCognitoCredentials credentials = this.getReactApplicationContext()
            .getNativeModule(AWSRNCognitoCredentials.class);
    if (credentials.getCredentialsProvider() == null) {
        throw new IllegalArgumentException("AWSCognitoCredentials is not initialized");
    }
    gson = new GsonBuilder().setFieldNamingStrategy(FieldNamingPolicy.UPPER_CAMEL_CASE)
            .registerTypeAdapter(ByteBuffer.class, AWSRNClientMarshaller.getSerializer())
            .registerTypeAdapter(ByteBuffer.class, AWSRNClientMarshaller.getDeserializer()).create();
    dynamodbClient = new AmazonDynamoDBClient(credentials.getCredentialsProvider(),
            new AWSRNClientConfiguration().withUserAgent("DynamoDB"));
    dynamodbClient.setRegion(Region.getRegion(Regions.fromName(options.getString("region"))));
}

From source file:com.amazonaws.reactnative.lambda.AWSRNLambdaClient.java

License:Open Source License

@ReactMethod
public void initWithOptions(final ReadableMap options) {
    if (!options.hasKey("region")) {
        throw new IllegalArgumentException("expected region key");
    }//from w w  w  .  j a  v  a2 s .  com
    final AWSRNCognitoCredentials credentials = this.getReactApplicationContext()
            .getNativeModule(AWSRNCognitoCredentials.class);
    if (credentials.getCredentialsProvider() == null) {
        throw new IllegalArgumentException("AWSCognitoCredentials is not initialized");
    }
    gson = new GsonBuilder().setFieldNamingStrategy(FieldNamingPolicy.UPPER_CAMEL_CASE)
            .registerTypeAdapter(ByteBuffer.class, AWSRNClientMarshaller.getSerializer())
            .registerTypeAdapter(ByteBuffer.class, AWSRNClientMarshaller.getDeserializer()).create();
    lambdaClient = new AWSLambdaClient(credentials.getCredentialsProvider(),
            new AWSRNClientConfiguration().withUserAgent("Lambda"));
    lambdaClient.setRegion(Region.getRegion(Regions.fromName(options.getString("region"))));
}