Example usage for com.google.gson GsonBuilder registerTypeAdapter

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

Introduction

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

Prototype

@SuppressWarnings({ "unchecked", "rawtypes" })
public GsonBuilder registerTypeAdapter(Type type, Object typeAdapter) 

Source Link

Document

Configures Gson for custom serialization or deserialization.

Usage

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  ww  .j  a v  a 2  s .  c  o  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;//  w w w. java  2s .  co 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.android.build.gradle.api.ApkOutput.java

License:Apache License

public static ImmutableList<SplitApkOutput> load(File inputFile) throws FileNotFoundException {

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(SplitApkOutput.class, new SplitApkOutput.JsonDeserializer());
    Gson gson = gsonBuilder.create();//  ww w  .  j ava  2 s . c om

    ImmutableList.Builder<SplitApkOutput> builder = ImmutableList.builder();

    for (SplitApkOutput vo : gson.fromJson(new FileReader(inputFile), SplitApkOutput[].class)) {
        builder.add(vo);
    }
    return builder.build();
}

From source file:com.android.build.gradle.internal.pipeline.SubStream.java

License:Apache License

public static Collection<SubStream> loadSubStreams(@NonNull File rootFolder) {
    final File jsonFile = new File(rootFolder, FN_FOLDER_CONTENT);
    if (!jsonFile.isFile()) {
        return ImmutableList.of();
    }/*  w  w w  . j a va 2 s. com*/

    try (FileReader reader = new FileReader(jsonFile)) {

        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.registerTypeAdapter(SubStream.class, new SubStreamAdapter());
        Gson gson = gsonBuilder.create();

        Type recordType = new TypeToken<List<SubStream>>() {
        }.getType();
        return gson.fromJson(reader, recordType);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.android.build.gradle.internal.pipeline.SubStream.java

License:Apache License

public static void save(@NonNull Collection<SubStream> subStreams, @NonNull File rootFolder)
        throws IOException {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(SubStream.class, new SubStreamAdapter());
    Gson gson = gsonBuilder.create();/*  ww w.  ja v a 2 s  .c  o m*/

    // just in case
    FileUtils.mkdirs(rootFolder);
    Files.write(gson.toJson(subStreams), new File(rootFolder, FN_FOLDER_CONTENT), Charsets.UTF_8);
}

From source file:com.android.build.gradle.internal.scope.BuildOutputs.java

License:Apache License

/**
 * Persists the passed output types and split output to a {@link String} using gson.
 *
 * @param projectPath path to relativize output file paths against.
 * @param outputTypes the output types to persist.
 * @param splitOutputs the outputs organized per output type
 * @return a json String./*from  ww  w. j av a2s . c  om*/
 */
public static String persist(Path projectPath, ImmutableList<VariantScope.OutputType> outputTypes,
        SetMultimap<VariantScope.OutputType, BuildOutput> splitOutputs) {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(ApkInfo.class, new BuildOutputs.ApkInfoAdapter());
    gsonBuilder.registerTypeAdapter(VariantScope.TaskOutputType.class,
            new BuildOutputs.OutputTypeTypeAdapter());
    gsonBuilder.registerTypeAdapter(VariantScope.AnchorOutputType.class,
            new BuildOutputs.OutputTypeTypeAdapter());
    Gson gson = gsonBuilder.create();
    // flatten and relativize the file paths to be persisted.
    List<BuildOutput> buildOutputs = outputTypes.stream().map(splitOutputs::get).flatMap(Collection::stream)
            .map(buildOutput -> new BuildOutput(buildOutput.getType(), buildOutput.getApkInfo(),
                    projectPath.relativize(buildOutput.getOutputPath()), buildOutput.getProperties()))
            .collect(Collectors.toList());
    return gson.toJson(buildOutputs);
}

From source file:com.android.build.gradle.internal.scope.BuildOutputs.java

License:Apache License

@NonNull
private static Collection<BuildOutput> load(@NonNull Path projectPath, @NonNull Reader reader) {
    GsonBuilder gsonBuilder = new GsonBuilder();

    gsonBuilder.registerTypeAdapter(ApkInfo.class, new ApkInfoAdapter());
    gsonBuilder.registerTypeAdapter(VariantScope.OutputType.class, new OutputTypeTypeAdapter());
    Gson gson = gsonBuilder.create();/*w  w  w .  jav a2s.c o  m*/
    Type recordType = new TypeToken<List<BuildOutput>>() {
    }.getType();
    Collection<BuildOutput> buildOutputs = gson.fromJson(reader, recordType);
    // resolve the file path to the current project location.
    return buildOutputs.stream()
            .map(buildOutput -> new BuildOutput(buildOutput.getType(), buildOutput.getApkInfo(),
                    projectPath.resolve(buildOutput.getOutputPath()), buildOutput.getProperties()))
            .collect(Collectors.toList());
}

From source file:com.android.common.ide.common.blame.MessageJsonSerializer.java

License:Apache License

public static void registerTypeAdapters(GsonBuilder builder) {
    builder.registerTypeAdapter(SourceFile.class, new SourceFileJsonTypeAdapter());
    builder.registerTypeAdapter(SourcePosition.class, new SourcePositionJsonTypeAdapter());
    builder.registerTypeAdapter(SourceFilePosition.class, new SourceFilePositionJsonSerializer());
    builder.registerTypeAdapter(Message.class, new MessageJsonSerializer());
}

From source file:com.android.manifmerger.Actions.java

License:Apache License

@SuppressWarnings("SpellCheckingInspection")
@NonNull/*  www .j  a  va 2 s.c o  m*/
private static Gson getGsonParser() {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.enableComplexMapKeySerialization();
    gsonBuilder.registerTypeAdapter(XmlNode.NodeName.class, new NodeNameDeserializer());
    MessageJsonSerializer.registerTypeAdapters(gsonBuilder);
    return gsonBuilder.create();
}

From source file:com.android.volley.GsonUtils.java

License:Open Source License

/**
 * Create the standard {@link com.google.gson.Gson} configuration
 *
 * @param serializeNulls/*from w  ww.  j av a2s .c om*/
 *            whether nulls should be serialized
 *
 * @return created gson, never null
 */
public static final Gson createGson(final boolean serializeNulls) {
    final GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapter(Date.class, new DateFormatter());
    builder.enableComplexMapKeySerialization();
    //      builder.setFieldNamingPolicy(LOWER_CASE_WITH_UNDERSCORES);
    if (serializeNulls)
        builder.serializeNulls();
    return builder.create();
    //        private static final Gson gson  = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().enableComplexMapKeySerialization()
    //                .serializeNulls().setDateFormat("yyyy-MM-dd HH:mm:ss:SSS ")
    //                .setPrettyPrinting().setVersion(1.0).create();
}