List of usage examples for com.google.gson JsonPrimitive JsonPrimitive
public JsonPrimitive(Character c)
From source file:com.github.jsdossier.Flags.java
License:Apache License
private void addToArray(String key, String value) { addToArray(key, new JsonPrimitive(value)); }
From source file:com.github.sheigutn.pushbullet.gson.RuntimeTypeAdapterFactory.java
License:Apache License
public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) { if (type.getRawType() != baseType) { return null; }//w w w. ja va2s . c o m if (baseDelegateAdapter == null) { baseDelegateAdapter = gson.getDelegateAdapter(RuntimeTypeAdapterFactory.this, TypeToken.get(baseType)); } final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<String, TypeAdapter<?>>(); final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<Class<?>, TypeAdapter<?>>(); for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) { TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue())); labelToDelegate.put(entry.getKey(), delegate); subtypeToDelegate.put(entry.getValue(), delegate); } return new TypeAdapter<R>() { @SuppressWarnings("unchecked") @Override public R read(JsonReader in) throws IOException { JsonElement jsonElement = Streams.parse(in); JsonElement labelJsonElement = jsonElement.getAsJsonObject().get(typeFieldName); //remove(typeFieldName) changed to get(typeFieldName) if (labelJsonElement == null) { return (R) baseDelegateAdapter.fromJsonTree(jsonElement); } String label = labelJsonElement.getAsString(); @SuppressWarnings("unchecked") // registration requires that subtype extends T TypeAdapter<R> delegate = (TypeAdapter<R>) labelToDelegate.get(label); if (delegate == null) { throw new JsonParseException("cannot deserialize " + baseType + " subtype named " + label + "; did you forget to register a subtype?"); } return delegate.fromJsonTree(jsonElement); } @Override public void write(JsonWriter out, R value) throws IOException { Class<?> srcType = value.getClass(); String label = subtypeToLabel.get(srcType); @SuppressWarnings("unchecked") // registration requires that subtype extends T TypeAdapter<R> delegate = (TypeAdapter<R>) subtypeToDelegate.get(srcType); if (delegate == null) { throw new JsonParseException( "cannot serialize " + srcType.getName() + "; did you forget to register a subtype?"); } JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject(); //if (jsonObject.has(typeFieldName)) { // throw new JsonParseException("cannot serialize " + srcType.getName() // + " because it already defines a field named " + typeFieldName); <-- Commented //} JsonObject clone = new JsonObject(); clone.add(typeFieldName, new JsonPrimitive(label)); for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) { clone.add(e.getKey(), e.getValue()); } Streams.write(clone, out); } }.nullSafe(); }
From source file:com.gmail.tracebachi.DeltaSkins.Shared.MojangApi.java
License:Open Source License
private String convertUuidRequestsToStringPayload() { synchronized (uuidRequestLock) { Iterator<String> iterator = uuidRequests.iterator(); JsonArray array = new JsonArray(); for (int i = 0; i < 100 && iterator.hasNext(); ++i) { String next = iterator.next(); if (next != null && !next.isEmpty()) { array.add(new JsonPrimitive(next)); }/* w w w . j a va 2 s . co m*/ iterator.remove(); } return gson.toJson(array); } }
From source file:com.goodow.realtime.server.model.DeltaSerializer.java
License:Apache License
public static JsonElement dataToClientJson(Delta<String> data, long resultingRevision) { Preconditions.checkArgument(resultingRevision <= MAX_DOUBLE_INTEGER, "Resulting revision %s is too large", resultingRevision);//w w w .java 2 s . c o m // Assume payload is JSON, and parse it to avoid nested json. // TODO: Consider using Delta<JSONObject> instead. // The reason I haven't done it yet is because it's not immutable, // and also for reasons described in Delta. JsonElement payloadJson; try { payloadJson = new JsonParser().parse(data.getPayload()); } catch (JsonParseException e) { throw new IllegalArgumentException("Invalid payload for " + data, e); } JsonArray json = new JsonArray(); try { Preconditions.checkArgument(resultingRevision >= 0, "invalid rev %s", resultingRevision); json.add(new JsonPrimitive(resultingRevision)); long sanityCheck = json.get(0).getAsLong(); if (sanityCheck != resultingRevision) { throw new AssertionError("resultingRevision " + resultingRevision + " not losslessly represented in JSON, got back " + sanityCheck); } json.add(new JsonPrimitive(data.getSession().userId)); json.add(new JsonPrimitive(data.getSession().sessionId)); json.add(payloadJson); return json; } catch (JsonParseException e) { throw new Error(e); } }
From source file:com.google.api.ads.adwords.keywordoptimizer.api.JsonUtil.java
License:Open Source License
/** * Initializes Gson to convert objects to and from JSON. This method customizes a "plain" Gson by * adding appropriate exclusions strategies / adapters as needed in this project for a "pretty" * output. /*from w w w . j av a2 s. c o m*/ */ private static Gson initGson(boolean prettyPrint) { GsonBuilder builder = new GsonBuilder(); // Exclude superclasses. ExclusionStrategy superclassExclusionStrategy = new SuperclassExclusionStrategy(); builder.addDeserializationExclusionStrategy(superclassExclusionStrategy); builder.addSerializationExclusionStrategy(superclassExclusionStrategy); // Exclude underscore fields in client lib objects. ExclusionStrategy underscoreExclusionStrategy = new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes field) { if (field.getName().startsWith("_")) { return true; } return false; } @Override public boolean shouldSkipClass(Class<?> clazz) { return false; } }; builder.addDeserializationExclusionStrategy(underscoreExclusionStrategy); builder.addSerializationExclusionStrategy(underscoreExclusionStrategy); // Render KeywordCollection as an array of KeywordInfos. builder.registerTypeAdapter(KeywordCollection.class, new JsonSerializer<KeywordCollection>() { @Override public JsonElement serialize(KeywordCollection src, java.lang.reflect.Type typeOfSrc, JsonSerializationContext context) { JsonArray out = new JsonArray(); for (KeywordInfo info : src.getListSortedByScore()) { out.add(context.serialize(info)); } return out; } }); // Render Money as a primitive. builder.registerTypeAdapter(Money.class, new JsonSerializer<Money>() { @Override public JsonElement serialize(Money src, java.lang.reflect.Type typeOfSrc, JsonSerializationContext context) { JsonElement out = new JsonPrimitive(src.getMicroAmount() / 1000000); return out; } }); // Render Keyword in a simple way. builder.registerTypeAdapter(Keyword.class, new JsonSerializer<Keyword>() { @Override public JsonElement serialize(Keyword src, java.lang.reflect.Type typeOfSrc, JsonSerializationContext context) { JsonObject out = new JsonObject(); out.addProperty("text", src.getText()); out.addProperty("matchtype", src.getMatchType().toString()); return out; } }); // Render Throwable in a simple way (for all subclasses). builder.registerTypeHierarchyAdapter(Throwable.class, new JsonSerializer<Throwable>() { @Override public JsonElement serialize(Throwable src, java.lang.reflect.Type typeOfSrc, JsonSerializationContext context) { JsonObject out = new JsonObject(); out.addProperty("message", src.getMessage()); out.addProperty("type", src.getClass().getName()); JsonArray stack = new JsonArray(); for (StackTraceElement stackTraceElement : src.getStackTrace()) { JsonObject stackElem = new JsonObject(); stackElem.addProperty("file", stackTraceElement.getFileName()); stackElem.addProperty("line", stackTraceElement.getLineNumber()); stackElem.addProperty("method", stackTraceElement.getMethodName()); stackElem.addProperty("class", stackTraceElement.getClassName()); stack.add(stackElem); } out.add("stack", stack); if (src.getCause() != null) { out.add("cause", context.serialize(src.getCause())); } return out; } }); if (prettyPrint) { builder.setPrettyPrinting(); } return builder.create(); }
From source file:com.google.appinventor.components.runtime.ProbeBase.java
License:Open Source License
protected void saveToDB(IJsonObject completeProbeUri, IJsonObject data) { Log.i(TAG, "Writing data: " + completeProbeUri + ": " + data.toString()); final JsonObject dataObject = data.getAsJsonObject(); dataObject.add("probe", completeProbeUri.get(RuntimeTypeAdapterFactory.TYPE)); dataObject.add("timezoneOffset", new JsonPrimitive(localOffsetSeconds)); // nice // move//from w w w . j av a 2 s . c o m final long timestamp = data.get(BaseProbeKeys.TIMESTAMP).getAsLong(); final String probeName = completeProbeUri.get("@type").getAsString(); Bundle b = new Bundle(); b.putString(NameValueDatabaseService.DATABASE_NAME_KEY, PROBE_BASE_NAME); b.putLong(NameValueDatabaseService.TIMESTAMP_KEY, timestamp); b.putString(NameValueDatabaseService.NAME_KEY, probeName); b.putString(NameValueDatabaseService.VALUE_KEY, dataObject.toString()); Intent i = new Intent(mBoundFunfManager, NameValueDatabaseService.class); i.setAction(DatabaseService.ACTION_RECORD); i.putExtras(b); mBoundFunfManager.startService(i); }
From source file:com.google.belay.server.CapabilityAdapter.java
License:Open Source License
@Override public JsonElement serialize(Capability cap, Type typeOfT, JsonSerializationContext context) { JsonObject obj = new JsonObject(); obj.add("@", new JsonPrimitive(cap.getCapUrl().toString())); return obj;/*w w w . j a v a2 s . c o m*/ }
From source file:com.google.cloud.solutions.sampleapps.orchestration.orchestrator.server.GceInstanceCreator.java
License:Open Source License
/** * Makes the payload for creating an instance. * * @param instanceName the name of the instance. * @return the payload for the POST request to create a new instance. *///from w w w . j ava 2s.co m String createPayload_instance(String instanceName, String bootDiskName, Map<String, String> configProperties) { JsonObject json = new JsonObject(); json.addProperty("kind", "compute#instance"); json.addProperty("name", instanceName); json.addProperty("machineType", ConfigProperties.urlPrefixWithProjectAndZone + "/machineTypes/" + configProperties.get("machineType")); JsonObject disksElem = new JsonObject(); disksElem.addProperty("kind", "compute#attachedDisk"); disksElem.addProperty("boot", true); disksElem.addProperty("type", "PERSISTENT"); disksElem.addProperty("mode", "READ_WRITE"); disksElem.addProperty("deviceName", bootDiskName); disksElem.addProperty("zone", ConfigProperties.urlPrefixWithProjectAndZone); disksElem.addProperty("source", ConfigProperties.urlPrefixWithProjectAndZone + "/disks/" + bootDiskName); JsonArray jsonAr = new JsonArray(); jsonAr.add(disksElem); json.add("disks", jsonAr); JsonObject networkInterfacesObj = new JsonObject(); networkInterfacesObj.addProperty("kind", "compute#instanceNetworkInterface"); networkInterfacesObj.addProperty("network", ConfigProperties.urlPrefixWithProject + "/global/networks/default"); JsonObject accessConfigsObj = new JsonObject(); accessConfigsObj.addProperty("name", "External NAT"); accessConfigsObj.addProperty("type", "ONE_TO_ONE_NAT"); JsonArray accessConfigsAr = new JsonArray(); accessConfigsAr.add(accessConfigsObj); networkInterfacesObj.add("accessConfigs", accessConfigsAr); JsonArray networkInterfacesAr = new JsonArray(); networkInterfacesAr.add(networkInterfacesObj); json.add("networkInterfaces", networkInterfacesAr); JsonObject serviceAccountsObj = new JsonObject(); serviceAccountsObj.addProperty("kind", "compute#serviceAccount"); serviceAccountsObj.addProperty("email", "default"); JsonArray scopesAr = new JsonArray(); scopesAr.add(new JsonPrimitive("https://www.googleapis.com/auth/userinfo.email")); scopesAr.add(new JsonPrimitive("https://www.googleapis.com/auth/compute")); scopesAr.add(new JsonPrimitive("https://www.googleapis.com/auth/devstorage.full_control")); serviceAccountsObj.add("scopes", scopesAr); JsonArray serviceAccountsAr = new JsonArray(); serviceAccountsAr.add(serviceAccountsObj); json.add("serviceAccounts", serviceAccountsAr); JsonObject metadataObj = new JsonObject(); JsonArray mdItemsAr = new JsonArray(); JsonObject mdItemsObj = new JsonObject(); mdItemsObj.addProperty("key", "startup-script-url"); mdItemsObj.addProperty("value", configProperties.get("startupScript")); mdItemsAr.add(mdItemsObj); metadataObj.add("items", mdItemsAr); json.add("metadata", metadataObj); String payload = json.toString(); return payload; }
From source file:com.google.dart.server.generated.types.CompletionSuggestion.java
License:Open Source License
public JsonObject toJson() { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("kind", kind); jsonObject.addProperty("relevance", relevance); jsonObject.addProperty("completion", completion); jsonObject.addProperty("selectionOffset", selectionOffset); jsonObject.addProperty("selectionLength", selectionLength); jsonObject.addProperty("isDeprecated", isDeprecated); jsonObject.addProperty("isPotential", isPotential); if (docSummary != null) { jsonObject.addProperty("docSummary", docSummary); }//from ww w . ja va 2s .com if (docComplete != null) { jsonObject.addProperty("docComplete", docComplete); } if (declaringType != null) { jsonObject.addProperty("declaringType", declaringType); } if (element != null) { jsonObject.add("element", element.toJson()); } if (returnType != null) { jsonObject.addProperty("returnType", returnType); } if (parameterNames != null) { JsonArray jsonArrayParameterNames = new JsonArray(); for (String elt : parameterNames) { jsonArrayParameterNames.add(new JsonPrimitive(elt)); } jsonObject.add("parameterNames", jsonArrayParameterNames); } if (parameterTypes != null) { JsonArray jsonArrayParameterTypes = new JsonArray(); for (String elt : parameterTypes) { jsonArrayParameterTypes.add(new JsonPrimitive(elt)); } jsonObject.add("parameterTypes", jsonArrayParameterTypes); } if (requiredParameterCount != null) { jsonObject.addProperty("requiredParameterCount", requiredParameterCount); } if (hasNamedParameters != null) { jsonObject.addProperty("hasNamedParameters", hasNamedParameters); } if (parameterName != null) { jsonObject.addProperty("parameterName", parameterName); } if (parameterType != null) { jsonObject.addProperty("parameterType", parameterType); } if (importUri != null) { jsonObject.addProperty("importUri", importUri); } return jsonObject; }
From source file:com.google.dart.server.generated.types.ExtractLocalVariableFeedback.java
License:Open Source License
public JsonObject toJson() { JsonObject jsonObject = new JsonObject(); JsonArray jsonArrayNames = new JsonArray(); for (String elt : names) { jsonArrayNames.add(new JsonPrimitive(elt)); }/* w w w. j av a 2 s.c om*/ jsonObject.add("names", jsonArrayNames); JsonArray jsonArrayOffsets = new JsonArray(); for (int elt : offsets) { jsonArrayOffsets.add(new JsonPrimitive(elt)); } jsonObject.add("offsets", jsonArrayOffsets); JsonArray jsonArrayLengths = new JsonArray(); for (int elt : lengths) { jsonArrayLengths.add(new JsonPrimitive(elt)); } jsonObject.add("lengths", jsonArrayLengths); return jsonObject; }