Example usage for com.google.gson GsonBuilder GsonBuilder

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

Introduction

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

Prototype

public GsonBuilder() 

Source Link

Document

Creates a GsonBuilder instance that can be used to build Gson with various configuration settings.

Usage

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//w ww  .  ja v a 2s.  co 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.alignace.chargeio.mapper.JsonMapper.java

License:Apache License

private static Gson getGson() {

    if (gson == null) {

        GsonBuilder builder = new GsonBuilder();
        builder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        builder.registerTypeAdapter(IPaymentMethod.class, new IPaymentTypeAdapter());
        builder.registerTypeAdapter(TokenReferenceOption.class, new TokenReferenceAdapter());
        gson = builder.create();/*  ww  w .j a  v  a  2s. c  o  m*/
    }

    return gson;
}

From source file:com.aliyun.fs.oss.utils.OSSClientAgent.java

License:Apache License

@SuppressWarnings("unchecked")
private ObjectMetadata getObjectMetadata(String bucket, String key, boolean retry)
        throws IOException, ServiceException, ClientException {
    try {/* w  w  w . ja  v a  2  s  .  co m*/
        GsonBuilder builder = new GsonBuilder();
        builder.registerTypeAdapter(ObjectMetadata.class, new ObjectMetadataDeserializer());
        Gson gson = builder.create();

        Method method = this.ossClientClz.getMethod("getObjectMetadata", String.class, String.class);
        Object ret = method.invoke(this.ossClient, bucket, key);
        return gson.fromJson(gson.toJson(ret), ObjectMetadata.class);
    } catch (NoSuchMethodException e) {
        LOG.error(e.getMessage());
        return null;
    } catch (Exception e) {
        if (retry && updateOSSClient(e)) {
            return getObjectMetadata(bucket, key, false);
        } else {
            handleException(e);
            return null;
        }
    }
}

From source file:com.aliyun.fs.oss.utils.OSSClientAgent.java

License:Apache License

@SuppressWarnings("unchecked")
private OSSObject getObject(String bucket, String key, long start, long end, Configuration conf, boolean retry)
        throws IOException, ServiceException, ClientException {
    InputStream inputStream;/*from w  ww  .jav  a 2s  . c  o  m*/
    try {
        Class GetObjectRequestClz = ResourceLoader.getInstance().getUrlClassLoader(conf)
                .loadClass("com.aliyun.oss.model.GetObjectRequest");
        Constructor cons0 = GetObjectRequestClz.getConstructor(String.class, String.class);
        Object getObjRequest = cons0.newInstance(bucket, key);
        Method method0 = GetObjectRequestClz.getMethod("setRange", Long.TYPE, Long.TYPE);
        method0.invoke(getObjRequest, start, end);

        Method method = this.ossClientClz.getMethod("getObject", GetObjectRequestClz);
        Object ret = method.invoke(this.ossClient, getObjRequest);

        Class OSSObjectClz = ResourceLoader.getInstance().getUrlClassLoader(conf)
                .loadClass("com.aliyun.oss.model.OSSObject");
        Method method1 = OSSObjectClz.getMethod("getObjectContent");
        inputStream = (InputStream) method1.invoke(ret);

        GsonBuilder builder = new GsonBuilder();
        builder.registerTypeAdapter(ObjectMetadata.class, new ObjectMetadataDeserializer());
        Gson gson = builder.create();
        Method method2 = OSSObjectClz.getMethod("getObjectMetadata");
        Object metadata = method2.invoke(ret);
        ObjectMetadata objectMetadata = gson.fromJson(gson.toJson(metadata), ObjectMetadata.class);

        OSSObject ossObject = new OSSObject();
        ossObject.setBucketName(bucket);
        ossObject.setKey(key);
        ossObject.setObjectContent(inputStream);
        ossObject.setObjectMetadata(objectMetadata);
        return ossObject;
    } catch (Exception e) {
        if (retry && updateOSSClient(e)) {
            return getObject(bucket, key, start, end, conf, false);
        } else {
            handleException(e);
            return null;
        }
    }
}

From source file:com.almost50shades.shadesconnector.eventbrite.api.EventBriteImpl.java

public EventBriteImpl(String token, Database database) {
    gson = new GsonBuilder().create();
    builder = new UrlBuilder(token);
    client = new BasicClient();
    this.database = database;
}

From source file:com.amazonaws.devicefarm.android.referenceapp.Util.JsonParser.java

License:Open Source License

/**
 * Parses the JSON file into data models
 * @return List of DrawerCategory Models
 *///from   ww w . jav a2  s .c  o m
public List<DrawerCategoryModel> serializeJson() {
    try {
        Reader reader = new InputStreamReader(context.getResources().openRawResource(resId));
        Gson gson = new GsonBuilder().create();
        Type listType = new TypeToken<List<DrawerCategoryModel>>() {
        }.getType();
        List<DrawerCategoryModel> list = gson.fromJson(reader, listType);
        reader.close();
        return list;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

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  ww .  ja  va 2s.co 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 a2s . 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();
    lambdaClient = new AWSLambdaClient(credentials.getCredentialsProvider(),
            new AWSRNClientConfiguration().withUserAgent("Lambda"));
    lambdaClient.setRegion(Region.getRegion(Regions.fromName(options.getString("region"))));
}

From source file:com.amazonaws.reactnative.sns.AWSRNSNSClient.java

License:Open Source License

@ReactMethod
public void initWithOptions(final ReadableMap options) {
    if (!options.hasKey("region")) {
        throw new IllegalArgumentException("expected region key");
    }/*w w w. j ava 2  s  .co  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();
    snsClient = new AmazonSNSClient(credentials.getCredentialsProvider(),
            new AWSRNClientConfiguration().withUserAgent("SNS"));
    snsClient.setRegion(Region.getRegion(Regions.fromName(options.getString("region"))));
}

From source file:com.amazonaws.util.awsclientgenerator.generators.DirectFromC2jGenerator.java

License:Open Source License

public File generateSourceFromJson(String rawJson, String languageBinding, String serviceName)
        throws Exception {
    GsonBuilder gsonBuilder = new GsonBuilder();
    Gson gson = gsonBuilder.create();//  w  ww . ja v a  2s.c  o m
    C2jServiceModel c2jServiceModel = gson.fromJson(rawJson, C2jServiceModel.class);

    return mainClientGenerator.generateSourceFromC2jModel(c2jServiceModel, serviceName, languageBinding);
}