Example usage for com.google.gson GsonBuilder setVersion

List of usage examples for com.google.gson GsonBuilder setVersion

Introduction

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

Prototype

public GsonBuilder setVersion(double ignoreVersionsAfter) 

Source Link

Document

Configures Gson to enable versioning support.

Usage

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  ww .j a  va  2 s  . com*/
            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:cn.taop.utils.GSONUtils.java

License:Apache License

/**
 * ????? {@code JSON} ?// ww w .  j a  v a  2 s.c  om
 * <p />
 * <strong>???? <code>"{}"</code> ? <code>"[]"</code>
 * </strong>
 * 
 * @param target 
 * @param targetType 
 * @param isSerializeNulls ?? {@code null} 
 * @param version ?
 * @param datePattern ??
 * @param excludesFieldsWithoutExpose ? {@literal @Expose} 
 * @return  {@code JSON} ?
 * @since 1.0
 */
public static String toJson(Object target, Type targetType, boolean isSerializeNulls, Double version,
        String datePattern, boolean excludesFieldsWithoutExpose) {
    if (target == null)
        return EMPTY_JSON;
    GsonBuilder builder = new GsonBuilder();
    if (isSerializeNulls)
        builder.serializeNulls();
    if (version != null)
        builder.setVersion(version.doubleValue());
    if (StringUtils.isBlank(datePattern))
        datePattern = DEFAULT_DATE_PATTERN;
    builder.setDateFormat(datePattern);
    if (excludesFieldsWithoutExpose)
        builder.excludeFieldsWithoutExposeAnnotation();
    return toJson(target, targetType, builder);
}

From source file:com.arvato.thoroughly.util.CommonUtils.java

License:Open Source License

/**
 * @param whetherExposeAnnotation//from  w  w  w.  j  a  va2  s  .  c  o m
 * @param dateFormat
 * @return Gson instance
 */
public static Gson getGsonByBuilder(boolean whetherExposeAnnotation, String dateFormat) {
    GsonBuilder gsonBuilder = new GsonBuilder();
    if (whetherExposeAnnotation) {
        //Export only entity with @Expose annotation properties
        gsonBuilder.excludeFieldsWithoutExposeAnnotation();
    }

    gsonBuilder.enableComplexMapKeySerialization();

    if (StringUtils.isEmpty(dateFormat)) {
        dateFormat = "yyyy-MM-dd HH:mm:ss";
    }
    gsonBuilder.setDateFormat(dateFormat);//.serializeNulls()
    gsonBuilder.setVersion(1.0);

    return gsonBuilder.create();
}

From source file:com.avatarproject.core.storage.Serializer.java

License:Open Source License

/**
 * Gets the GSON instance for serializing
 * @return/*from  w  w  w .j  a  v  a2  s.  co m*/
 */
private static Gson getGson() {
    GsonBuilder builder = new GsonBuilder();
    builder.setVersion(version);
    builder.serializeNulls();
    builder.setPrettyPrinting();
    builder.enableComplexMapKeySerialization();
    builder.excludeFieldsWithoutExposeAnnotation();
    return builder.create();
}

From source file:com.cloud.consoleproxy.ConsoleProxyManagerImpl.java

License:Apache License

private boolean hasPreviousSession(ConsoleProxyVO proxy, VMInstanceVO vm) {

    ConsoleProxyStatus status = null;//from   w  w w. j a va  2 s.  co m
    try {
        GsonBuilder gb = new GsonBuilder();
        gb.setVersion(1.3);
        Gson gson = gb.create();

        byte[] details = proxy.getSessionDetails();
        status = gson.fromJson(details != null ? new String(details, Charset.forName("US-ASCII")) : null,
                ConsoleProxyStatus.class);
    } catch (Throwable e) {
        s_logger.warn("Unable to parse proxy session details : " + proxy.getSessionDetails());
    }

    if (status != null && status.getConnections() != null) {
        ConsoleProxyConnectionInfo[] connections = status.getConnections();
        for (int i = 0; i < connections.length; i++) {
            long taggedVmId = 0;
            if (connections[i].tag != null) {
                try {
                    taggedVmId = Long.parseLong(connections[i].tag);
                } catch (NumberFormatException e) {
                    s_logger.warn("Unable to parse console proxy connection info passed through tag: "
                            + connections[i].tag, e);
                }
            }
            if (taggedVmId == vm.getId()) {
                return true;
            }
        }

        //
        // even if we are not in the list, it may because we haven't
        // received load-update yet
        // wait until session time
        //
        if (DateUtil.currentGMTTime().getTime()
                - vm.getProxyAssignTime().getTime() < _proxySessionTimeoutValue) {
            return true;
        }

        return false;
    } else {
        s_logger.error("No proxy load info on an overloaded proxy ?");
        return false;
    }
}

From source file:com.cloud.consoleproxy.ConsoleProxyManagerImpl.java

License:Apache License

public void onLoadAnswer(ConsoleProxyLoadAnswer answer) {
    if (answer.getDetails() == null) {
        return;/*from   w ww . j  a  va  2  s .  c  om*/
    }

    ConsoleProxyStatus status = null;
    try {
        GsonBuilder gb = new GsonBuilder();
        gb.setVersion(1.3);
        Gson gson = gb.create();
        status = gson.fromJson(answer.getDetails(), ConsoleProxyStatus.class);
    } catch (Throwable e) {
        s_logger.warn("Unable to parse load info from proxy, proxy vm id : " + answer.getProxyVmId()
                + ", info : " + answer.getDetails());
    }

    if (status != null) {
        int count = 0;
        if (status.getConnections() != null) {
            count = status.getConnections().length;
        }

        byte[] details = null;
        if (answer.getDetails() != null) {
            details = answer.getDetails().getBytes(Charset.forName("US-ASCII"));
        }
        _consoleProxyDao.update(answer.getProxyVmId(), count, DateUtil.currentGMTTime(), details);
    } else {
        if (s_logger.isTraceEnabled()) {
            s_logger.trace("Unable to get console proxy load info, id : " + answer.getProxyVmId());
        }

        _consoleProxyDao.update(answer.getProxyVmId(), 0, DateUtil.currentGMTTime(), null);
        // TODO : something is wrong with the VM, restart it?
    }
}

From source file:com.cloud.serializer.GsonHelper.java

License:Apache License

static Gson setDefaultGsonConfig(GsonBuilder builder) {
    builder.setVersion(1.5);
    ArrayTypeAdaptor<Command> cmdAdaptor = new ArrayTypeAdaptor<Command>();
    builder.registerTypeAdapter(Command[].class, cmdAdaptor);
    ArrayTypeAdaptor<Answer> ansAdaptor = new ArrayTypeAdaptor<Answer>();
    builder.registerTypeAdapter(Answer[].class, ansAdaptor);
    builder.registerTypeAdapter(new TypeToken<List<PortConfig>>() {
    }.getType(), new PortConfigListTypeAdaptor());
    builder.registerTypeAdapter(new TypeToken<Pair<Long, Long>>() {
    }.getType(), new NwGroupsCommandTypeAdaptor());
    Gson gson = builder.create();/*from w  w  w.  ja  v a2  s .  c om*/
    cmdAdaptor.initGson(gson);
    ansAdaptor.initGson(gson);
    return gson;
}

From source file:com.framework.util.JSONUtil.java

License:Apache License

/**
 * ????? {@code JSON} ?//from w  ww .  j ava2 s  .  c o  m
 * <p />
 * <strong>???? <code>"{}"</code> ? <code>"[]"</code>
 * </strong>
 * 
 * @param target 
 * @param targetType 
 * @param isSerializeNulls ?? {@code null} 
 * @param version ?
 * @param datePattern ??
 * @param excludesFieldsWithoutExpose ? {@literal @Expose} 
 * @return  {@code JSON} ?
 * @since 1.0
 */
public static String toJson(Object target, Type targetType, boolean isSerializeNulls, Double version,
        String datePattern, boolean excludesFieldsWithoutExpose) {
    if (target == null)
        return EMPTY_JSON;
    GsonBuilder builder = new GsonBuilder();
    if (isSerializeNulls)
        builder.serializeNulls();
    if (version != null)
        builder.setVersion(version.doubleValue());
    if (Tools.isEmpty(datePattern))
        datePattern = DEFAULT_DATE_PATTERN;
    builder.setDateFormat(datePattern);
    if (excludesFieldsWithoutExpose)
        builder.excludeFieldsWithoutExposeAnnotation();
    return toJson(target, targetType, builder);
}

From source file:com.hmwg.utils.GSONUtils.java

License:Apache License

/**
 * ????? {@code JSON} ?/*from ww  w .  j  a  va  2  s .  c  om*/
 * <p />
 * <strong>???? <code>"{}"</code> ?
 * <code>"[]"</code> </strong>
 * 
 * @param target
 *            
 * @param targetType
 *            
 * @param isSerializeNulls
 *            ?? {@code null} 
 * @param version
 *            ?
 * @param datePattern
 *            ??
 * @param excludesFieldsWithoutExpose
 *            ? {@literal @Expose} 
 * @return  {@code JSON} ?
 * @since 1.0
 */
public static String toJson(Object target, Type targetType, boolean isSerializeNulls, Double version,
        String datePattern, boolean excludesFieldsWithoutExpose) {
    if (target == null) {
        return EMPTY_JSON;
    }
    GsonBuilder builder = new GsonBuilder();
    if (isSerializeNulls) {
        builder.serializeNulls();
    }
    if (version != null) {
        builder.setVersion(version.doubleValue());
    }
    if (isBlankString(datePattern)) {
        datePattern = DEFAULT_DATE_PATTERN;
    }
    builder.setDateFormat(datePattern);
    if (excludesFieldsWithoutExpose) {
        builder.excludeFieldsWithoutExposeAnnotation();
    }
    return toJson(target, targetType, builder);
}

From source file:com.hybris.datahub.outbound.utils.CommonUtils.java

License:Open Source License

/**
 * @param whetherExposeAnnotation//from w w  w .java 2s. c om
 * @param dateFormat
 * @return Gson instance
 */
public static Gson getGsonByBuilder(final boolean whetherExposeAnnotation, String dateFormat) {
    final GsonBuilder gsonBuilder = new GsonBuilder();
    if (whetherExposeAnnotation) {
        gsonBuilder.excludeFieldsWithoutExposeAnnotation();
    }

    gsonBuilder.enableComplexMapKeySerialization();

    if (StringUtils.isEmpty(dateFormat)) {
        dateFormat = "yyyy-MM-dd HH:mm:ss";
    }
    gsonBuilder.serializeNulls().setDateFormat(dateFormat);
    gsonBuilder.setVersion(1.0);
    //      gsonBuilder.disableHtmlEscaping();
    return gsonBuilder.create();
}