Java Code Examples for com.google.gson.GsonBuilder#create()

The following examples show how to use com.google.gson.GsonBuilder#create() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: IntegrationMockClient.java    From product-private-paas with Apache License 2.0 6 votes vote down vote up
public boolean terminateInstance(String instanceId) {
    try {
        if (log.isDebugEnabled()) {
            log.debug(String.format("Terminate instance: [instance-id] %s", instanceId));
        }
        URI uri = new URIBuilder(endpoint + INSTANCES_CONTEXT + instanceId).build();
        org.apache.stratos.mock.iaas.client.rest.HttpResponse response = doDelete(uri);
        if (response != null) {
            if ((response.getStatusCode() >= 200) && (response.getStatusCode() < 300)) {
                return true;
            } else {
                GsonBuilder gsonBuilder = new GsonBuilder();
                Gson gson = gsonBuilder.create();
                org.apache.stratos.mock.iaas.domain.ErrorResponse errorResponse = gson.fromJson(response.getContent(), org.apache.stratos.mock.iaas.domain.ErrorResponse.class);
                if (errorResponse != null) {
                    throw new RuntimeException(errorResponse.getErrorMessage());
                }
            }
        }
        throw new RuntimeException("An unknown error occurred");
    } catch (Exception e) {
        String message = "Could not start mock instance";
        throw new RuntimeException(message, e);
    }
}
 
Example 2
Source File: Api.java    From CSCI4669-Fall15-Android with Apache License 2.0 6 votes vote down vote up
public static List<Post> getPosts() throws IOException {
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder()
            .url("http://jsonplaceholder.typicode.com/posts")
            .build();

    Response response = client.newCall(request).execute();

    String json = response.body().string();

    GsonBuilder gsonBuilder = new GsonBuilder();
    Gson gson = gsonBuilder.create();
    List<Post> posts = new ArrayList<Post>();
    posts = Arrays.asList(gson.fromJson(json, Post[].class));

    return posts;
}
 
Example 3
Source File: JsonEncodedGradleMessageParser.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
@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;
    }
    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);
    }
}
 
Example 4
Source File: XGsonBuilder.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
public static Gson compactInstance() {
	if (null == COMPACTINSTANCE) {
		synchronized (XGsonBuilder.class) {
			if (null == COMPACTINSTANCE) {
				GsonBuilder gson = new GsonBuilder();
				gson.setDateFormat(DateTools.format_yyyyMMddHHmmss);
				gson.registerTypeAdapter(Integer.class, new IntegerDeserializer());
				gson.registerTypeAdapter(Double.class, new DoubleDeserializer());
				gson.registerTypeAdapter(Float.class, new FloatDeserializer());
				gson.registerTypeAdapter(Long.class, new LongDeserializer());
				gson.registerTypeAdapter(Date.class, new DateDeserializer());
				gson.registerTypeAdapter(Date.class, new DateSerializer());
				COMPACTINSTANCE = gson.create();
			}
		}
	}
	return COMPACTINSTANCE;
}
 
Example 5
Source File: GsonSerializationUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenUsingCustomDeserializer_whenFieldNotMatchesCriteria_thenIgnored() {
    final SourceClass sourceObject = new SourceClass(-1, "minus 1");
    final GsonBuilder gsonBuildr = new GsonBuilder();
    gsonBuildr.registerTypeAdapter(SourceClass.class, new IgnoringFieldsNotMatchingCriteriaSerializer());
    final Gson gson = gsonBuildr.create();
    final Type sourceObjectType = new TypeToken<SourceClass>() {
    }.getType();
    final String jsonString = gson.toJson(sourceObject, sourceObjectType);

    final String expectedResult = "{\"stringValue\":\"minus 1\"}";
    assertEquals(expectedResult, jsonString);
}
 
Example 6
Source File: ChannelServiceModelProvider.java    From packagedrone with Eclipse Public License 1.0 5 votes vote down vote up
protected Gson createGson ()
{
    final GsonBuilder builder = new GsonBuilder ();
    builder.setPrettyPrinting ();
    builder.serializeNulls ();
    builder.setDateFormat ( "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" );
    builder.registerTypeAdapter ( DeployGroup.class, new DeployGroupTypeAdapter () );
    builder.registerTypeAdapter ( MetaKey.class, MetaKeyTypeAdapter.INSTANCE );
    return builder.create ();
}
 
Example 7
Source File: ConsoleProxyManagerImpl.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
@Override
public void onLoadReport(ConsoleProxyLoadReportCommand cmd) {
    if (cmd.getLoadInfo() == null) {
        return;
    }

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

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

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

        _consoleProxyDao.update(cmd.getProxyVmId(), 0, DateUtil.currentGMTTime(), null);
    }
}
 
Example 8
Source File: Actions.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
private static Gson getGsonParser() {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.enableComplexMapKeySerialization();
    gsonBuilder.registerTypeAdapter(XmlNode.NodeName.class, new NodeNameDeserializer());
    gsonBuilder.registerTypeAdapter(ActionLocation.class, new ActionLocation.ActionLocationAdapter());
    return gsonBuilder.create();
}
 
Example 9
Source File: Config.java    From BukkitPE with GNU General Public License v3.0 5 votes vote down vote up
private void parseContent(String content) {
    switch (this.type) {
        case Config.PROPERTIES:
            this.parseProperties(content);
            break;
        case Config.JSON:
            GsonBuilder builder = new GsonBuilder();
            Gson gson = builder.create();
            this.config = new ConfigSection(gson.fromJson(content, new TypeToken<LinkedHashMap<String, Object>>() {
            }.getType()));
            break;
        case Config.YAML:
            DumperOptions dumperOptions = new DumperOptions();
            dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
            Yaml yaml = new Yaml(dumperOptions);
            this.config = new ConfigSection(yaml.loadAs(content, LinkedHashMap.class));
            if (this.config == null) {
                this.config = new ConfigSection();
            }
            break;
        // case Config.SERIALIZED
        case Config.ENUM:
            this.parseList(content);
            break;
        default:
            this.correct = false;
    }
}
 
Example 10
Source File: JsonFunctions.java    From jphp with Apache License 2.0 5 votes vote down vote up
@Immutable
public static String json_encode(Memory memory, int options) {
    GsonBuilder builder;
    if (options != 0) {
        MemorySerializer serializer = new MemorySerializer();
        builder = JsonExtension.createGsonBuilder(serializer);

        if ((options & JsonConstants.JSON_PRETTY_PRINT) == JsonConstants.JSON_PRETTY_PRINT) {
            builder.setPrettyPrinting();
        }

        if ((options & JsonConstants.JSON_HEX_TAG) != JsonConstants.JSON_HEX_TAG) {
            builder.disableHtmlEscaping();
        }

        if ((options & JsonConstants.JSON_FORCE_OBJECT) == JsonConstants.JSON_FORCE_OBJECT) {
            serializer.setForceObject(true);
        }

        if ((options & JsonConstants.JSON_NUMERIC_CHECK) == JsonConstants.JSON_NUMERIC_CHECK) {
            serializer.setNumericCheck(true);
        }

        if ((options & JsonConstants.JSON_UNESCAPED_UNICODE) == JsonConstants.JSON_UNESCAPED_UNICODE) {
            serializer.unescapedUnicode(true);
        }
    } else {
        builder = JsonExtension.DEFAULT_GSON_BUILDER;
    }

    Gson gson = builder.create();
    return gson.toJson(memory);
}
 
Example 11
Source File: VoxelGamesLibModule.java    From VoxelGamesLibv2 with MIT License 5 votes vote down vote up
@Provides
@Named("IgnoreExposedBS")
@Nonnull
public Gson getGsonWithoutExposed(@Nonnull Injector injector) {
    GsonBuilder builder = new GsonBuilder();
    addTypeAdapters(builder, injector);
    builder.setPrettyPrinting();
    return builder.create();
}
 
Example 12
Source File: ClientServlet.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public ClientServlet(LwM2mServer server, int securePort) {
    this.server = server;

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeHierarchyAdapter(Client.class, new ClientSerializer(securePort));
    gsonBuilder.registerTypeHierarchyAdapter(LwM2mResponse.class, new ResponseSerializer());
    gsonBuilder.registerTypeHierarchyAdapter(LwM2mNode.class, new LwM2mNodeSerializer());
    gsonBuilder.registerTypeHierarchyAdapter(LwM2mNode.class, new LwM2mNodeDeserializer());
    gsonBuilder.setDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
    this.gson = gsonBuilder.create();
}
 
Example 13
Source File: CatalogGsonHelper.java    From tajo with Apache License 2.0 5 votes vote down vote up
public static Gson getPrettyInstance() {
  if (gsonPretty == null) {
    GsonBuilder prettyBuilder = new GsonBuilder()
        .setPrettyPrinting()
        .excludeFieldsWithoutExposeAnnotation();
    GsonHelper.registerAdapters(prettyBuilder, registerAdapters());
    gsonPretty = prettyBuilder.create();
  }

  return gsonPretty;
}
 
Example 14
Source File: JsonDatasetBeanSerializer.java    From mr4c with Apache License 2.0 4 votes vote down vote up
public DataKeyBean deserializeDataKeyBean(String serializedKey) {
	GsonBuilder builder = new GsonBuilder();
	Gson gson = builder.create();
	return gson.fromJson(serializedKey, DataKeyBean.class);
}
 
Example 15
Source File: JsonDataSetProducer.java    From jpa-unit with Apache License 2.0 4 votes vote down vote up
public JsonDataSetProducer(final InputStream input) {
    super(input);
    final GsonBuilder gsonBuilder = new GsonBuilder();
    gson = gsonBuilder.create();
}
 
Example 16
Source File: HubBlacklistDAOFileImpl.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
GsonParser() {
 GsonBuilder builder = new GsonBuilder();
 builder.registerTypeAdapter(Date.class, new DateTypeAdapter());
 gson = builder.create();
}
 
Example 17
Source File: JsonProcessor.java    From jphp with Apache License 2.0 4 votes vote down vote up
public JsonProcessor(Environment env, GsonBuilder builder) {
    super(env);
    this.builder = builder;
    this.gson = builder.create();
}
 
Example 18
Source File: Converter.java    From cathode with Apache License 2.0 4 votes vote down vote up
public Converter() {
  GsonBuilder builder = new GsonBuilder();
  builder.registerTypeAdapter(Job.class, new JobSerializer());
  gson = builder.create();
}
 
Example 19
Source File: PersistanceController.java    From slide with MIT License 4 votes vote down vote up
public PersistanceController(Context c) {
    mPreferences = c.getSharedPreferences("data", 0);
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapterFactory(new GsonAdaptersState());
    mGson = gsonBuilder.create();
}
 
Example 20
Source File: JsonKeyspaceBeanSerializer.java    From mr4c with Apache License 2.0 4 votes vote down vote up
public KeyspaceBean deserializeKeyspaceBean(Reader reader) throws IOException {
	GsonBuilder builder = new GsonBuilder();
	Gson gson = builder.create();
	return gson.fromJson(reader, KeyspaceBean.class);
}