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.android.build.gradle.tasks.NdkBuildExternalNativeJsonGenerator.java

License:Apache License

@Override
void processBuildOutput(@NonNull String buildOutput, @NonNull String abi, int abiPlatformVersion)
        throws IOException {
    // Discover Application.mk if one exists next to Android.mk
    // If there is an Application.mk file next to Android.mk then pick it up.
    File applicationMk = new File(getMakeFile().getParent(), "Application.mk");

    // Write the captured ndk-build output to a file for diagnostic purposes.
    diagnostic("parse and convert ndk-build output to build configuration JSON");

    // Tasks, including the Exec task used to execute ndk-build, will execute in the same folder
    // as the module build.gradle. However, parsing of ndk-build output doesn't necessarily
    // happen within a task because it may be done at sync time. The parser needs to create
    // absolute paths for source files that have relative paths in the ndk-build output. For
    // this reason, we need to tell the parser the folder of the module build.gradle. This is
    // 'projectDir'.
    ///*from www.jav  a2s  . com*/
    // Example, if a project is set up as follows:
    //
    //   project/build.gradle
    //   project/app/build.gradle
    //
    // Then, right now, the current folder is 'project/' but ndk-build -n was executed in
    // 'project/app/'. For this reason, any relative paths in the ndk-build -n ouput will be
    // relative to 'project/app/' but a direct call now to getAbsolutePath() would produce a
    // path relative to 'project/' which is wrong.
    //
    // NOTE: CMake doesn't have the same issue because CMake JSON generation happens fully
    // within the Exec call which has 'project/app' as the current directory.
    NativeBuildConfigValue buildConfig = new NativeBuildConfigValueBuilder(getMakeFile(), projectDir)
            .addCommands(getBuildCommand(abi, abiPlatformVersion, applicationMk, false /* removeJobsFlag */),
                    getBuildCommand(abi, abiPlatformVersion, applicationMk, true /* removeJobsFlag */)
                            + " clean",
                    variantName, buildOutput)
            .build();

    if (applicationMk.exists()) {
        diagnostic("found application make file %s", applicationMk.getAbsolutePath());
        Preconditions.checkNotNull(buildConfig.buildFiles);
        buildConfig.buildFiles.add(applicationMk);
    }

    String actualResult = new GsonBuilder().registerTypeAdapter(File.class, new PlainFileGsonTypeAdaptor())
            .setPrettyPrinting().create().toJson(buildConfig);

    // Write the captured ndk-build output to JSON file
    File expectedJson = ExternalNativeBuildTaskUtils.getOutputJson(getJsonFolder(), abi);
    Files.write(actualResult, expectedJson, Charsets.UTF_8);
}

From source file:com.android.example.leanback.fastlane.LeanbackBrowseFragment.java

License:Open Source License

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .registerTypeAdapter(Date.class, new DateTypeAdapter()).create();

    RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint("https://hub.gdgx.io/api/v1/")
            .setConverter(new GsonConverter(gson)).build();

    HubApiService hubApiService = restAdapter.create(HubApiService.class);
    hubApiService.getAllGdes(this);
}

From source file:com.android.ide.common.blame.output.GradleMessageRewriter.java

License:Apache License

private static Gson createGson() {
    GsonBuilder gsonBuilder = new GsonBuilder();
    MessageJsonSerializer.registerTypeAdapters(gsonBuilder);
    return gsonBuilder.create();
}

From source file:com.android.ide.common.blame.parser.JsonEncodedGradleMessageParser.java

License:Apache License

@Override
public boolean parse(@NonNull String line, @NonNull OutputLineReader reader, @NonNull List<Message> messages,
        @NonNull ILogger logger) throws ParsingFailedException {
    Matcher m = MSG_PATTERN.matcher(line);
    if (!m.matches()) {
        return false;
    }/*from  w ww. j  a  v a 2s .  co m*/
    String json = m.group(1);
    if (json.trim().isEmpty()) {
        return false;
    }

    GsonBuilder gsonBuilder = new GsonBuilder();
    MessageJsonSerializer.registerTypeAdapters(gsonBuilder);
    Gson gson = gsonBuilder.create();
    try {
        Message msg = gson.fromJson(json, Message.class);
        messages.add(msg);
        return true;
    } catch (JsonParseException e) {
        throw new ParsingFailedException(e);
    }
}

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

License:Apache License

@NonNull
public String persist() throws IOException {
    //noinspection SpellCheckingInspection
    GsonBuilder gson = new GsonBuilder().setPrettyPrinting();
    gson.enableComplexMapKeySerialization();
    MessageJsonSerializer.registerTypeAdapters(gson);
    return gson.create().toJson(this);
}

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

License:Apache License

@SuppressWarnings("SpellCheckingInspection")
@NonNull/*from   w  w  w  .  j  a va  2  s  .  c om*/
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.sdk.core.operations.ServiceOperation.java

License:Open Source License

private T getResultFromJson(JSONObject jsonObject) {
    requireNonNull(jsonObject, "responseJson");
    final GsonBuilder builder = new GsonBuilder();
    final Gson gson = builder.create();

    Object obj = gson.fromJson(jsonObject.toString(), resultType);
    ensureNonNull(obj);//  w w w  . j a  v a  2  s . c o  m
    ensure(resultType.isAssignableFrom(obj.getClass()),
            "Expected type: " + resultType + " actual type: " + obj);

    return (T) obj;
}

From source file:com.android.tools.idea.stats.DistributionService.java

License:Apache License

@Nullable
private static List<Distribution> loadDistributionsFromJson(String jsonString) {
    Type fullRevisionType = new TypeToken<Revision>() {
    }.getType();/*w  w w .  jav a  2  s . co m*/
    GsonBuilder gsonBuilder = new GsonBuilder().registerTypeAdapter(fullRevisionType,
            new JsonDeserializer<Revision>() {
                @Override
                public Revision deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                        throws JsonParseException {
                    return Revision.parseRevision(json.getAsString());
                }
            });
    Gson gson = gsonBuilder.create();
    Type listType = new TypeToken<ArrayList<Distribution>>() {
    }.getType();
    try {
        return gson.fromJson(jsonString, listType);
    } catch (JsonParseException e) {
        LOG.error("Parse exception while reading distributions.json", e);
    }
    return null;
}

From source file:com.android.tools.idea.wizard.DistributionChartComponent.java

License:Apache License

@Nullable
private static List<Distribution> loadDistributionsFromJson(String jsonString) {
    Type fullRevisionType = new TypeToken<FullRevision>() {
    }.getType();//from w ww .ja  va  2s  . com
    GsonBuilder gsonBuilder = new GsonBuilder().registerTypeAdapter(fullRevisionType,
            new JsonDeserializer<FullRevision>() {
                @Override
                public FullRevision deserialize(JsonElement json, Type typeOfT,
                        JsonDeserializationContext context) throws JsonParseException {
                    return FullRevision.parseRevision(json.getAsString());
                }
            });
    Gson gson = gsonBuilder.create();
    Type listType = new TypeToken<ArrayList<Distribution>>() {
    }.getType();
    try {
        return gson.fromJson(jsonString, listType);
    } catch (JsonParseException e) {
        LOG.error(e);
    }
    return null;
}

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  a  2  s  . c  o m
 *            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();
}