List of usage examples for com.google.gson JsonPrimitive toString
@Override
public String toString()
From source file:net.nexustools.njs.JSON.java
License:Open Source License
public JSON(final Global global) { super(global); setHidden("stringify", new AbstractFunction(global) { public java.lang.String stringify(BaseObject object) { StringBuilder builder = new StringBuilder(); stringify(object, builder);/*w ww .j a va2 s. com*/ return builder.toString(); } public void stringify(BaseObject object, StringBuilder builder) { if (Utilities.isUndefined(object)) { builder.append("null"); return; } BaseObject toJSON = object.get("toJSON", OR_NULL); if (toJSON != null) stringify0(((BaseFunction) toJSON).call(object), builder); else stringify0(object, builder); } public void stringify0(BaseObject object, StringBuilder builder) { if (object instanceof GenericArray) { builder.append('['); if (((GenericArray) object).length() > 0) { stringify(object.get(0), builder); for (int i = 1; i < ((GenericArray) object).length(); i++) { builder.append(','); stringify(object.get(i), builder); } } builder.append(']'); } else if (object instanceof String.Instance) { builder.append('"'); builder.append(object.toString()); builder.append('"'); } else if (object instanceof Number.Instance) { double number = ((Number.Instance) object).value; if (Double.isNaN(number) || Double.isInfinite(number)) builder.append("null"); builder.append(object.toString()); } else if (object instanceof Boolean.Instance) builder.append(object.toString()); else { builder.append('{'); Iterator<java.lang.String> it = object.keys().iterator(); if (it.hasNext()) { java.lang.String key = it.next(); builder.append('"'); builder.append(key); builder.append("\":"); stringify(object.get(key), builder); if (it.hasNext()) { do { builder.append(','); key = it.next(); builder.append('"'); builder.append(key); builder.append("\":"); stringify(object.get(key), builder); } while (it.hasNext()); } } builder.append('}'); } } @Override public BaseObject call(BaseObject _this, BaseObject... params) { switch (params.length) { case 0: return Undefined.INSTANCE; case 1: if (params[0] == Undefined.INSTANCE) return Undefined.INSTANCE; return global.wrap(stringify(params[0])); default: return global.wrap("undefined"); } } @Override public java.lang.String name() { return "JSON_stringify"; } }); setHidden("parse", new AbstractFunction(global) { final Gson GSON; { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(BaseObject.class, new JsonDeserializer<BaseObject>() { @Override public BaseObject deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) throws JsonParseException { if (je.isJsonNull()) return Null.INSTANCE; if (je.isJsonPrimitive()) { JsonPrimitive primitive = je.getAsJsonPrimitive(); if (primitive.isBoolean()) return primitive.getAsBoolean() ? global.Boolean.TRUE : global.Boolean.FALSE; if (primitive.isNumber()) return global.wrap(primitive.getAsDouble()); if (primitive.isString()) return global.wrap(primitive.getAsString()); throw new UnsupportedOperationException(primitive.toString()); } if (je.isJsonObject()) { GenericObject go = new GenericObject(global); JsonObject jo = je.getAsJsonObject(); for (Map.Entry<java.lang.String, JsonElement> entry : jo.entrySet()) { go.set(entry.getKey(), deserialize(entry.getValue(), type, jdc)); } return go; } if (je.isJsonArray()) { JsonArray ja = je.getAsJsonArray(); BaseObject[] array = new BaseObject[ja.size()]; for (int i = 0; i < array.length; i++) { array[i] = deserialize(ja.get(i), type, jdc); } return new GenericArray(global, array); } throw new UnsupportedOperationException(je.toString()); } }); GSON = gsonBuilder.create(); } @Override public BaseObject call(BaseObject _this, BaseObject... params) { try { return GSON.fromJson(params[0].toString(), BaseObject.class); } catch (com.google.gson.JsonSyntaxException ex) { throw new Error.JavaException("SyntaxError", "Unexpected token", ex); } } @Override public java.lang.String name() { return "JSON_parse"; } }); }
From source file:org.helios.dashkuj.core.apiimpl.AbstractDashku.java
License:Open Source License
/** * Builds a post body in post body format to send the dirty fields for the passed domain object. * The field values are URL encoded. /*from w ww . j a v a 2 s .c om*/ * @param domainObject the domain object to generate the diff post for * @return the diff post body */ protected Buffer buildDirtyUpdatePost(AbstractDashkuDomainObject domainObject) { StringBuilder b = new StringBuilder(); JsonObject jsonDomainObject = GsonFactory.getInstance().newNoSerGson().toJsonTree(domainObject) .getAsJsonObject(); Set<String> fieldnames = domainObject.getDirtyFieldNames(); if (fieldnames.isEmpty()) return null; for (String dirtyFieldName : domainObject.getDirtyFieldNames()) { try { JsonPrimitive jp = jsonDomainObject.getAsJsonPrimitive(dirtyFieldName); String value = null; if (jp.isString()) { value = URLEncoder.encode(jp.getAsString(), "UTF-8"); } else if (jp.isNumber()) { value = "" + jp.getAsNumber(); } else if (jp.isBoolean()) { value = "" + jp.getAsBoolean(); } else { value = jp.toString(); } b.append(dirtyFieldName).append("=").append(value).append("&"); } catch (Exception ex) { throw new RuntimeException("Failed to encode dirty field [" + dirtyFieldName + "]", ex); } } b.deleteCharAt(b.length() - 1); try { String encoded = b.toString(); //URLEncoder.encode(b.toString(), "UTF-8"); log.info("Update Post:[\n\t{}\n]", encoded); return new Buffer(encoded); } catch (Exception e) { throw new RuntimeException(e); // ain't happening } }
From source file:org.hibernate.search.elasticsearch.query.impl.JsonDrivenProjection.java
License:LGPL
@Override public Object convertHit(JsonObject hit, ConversionContext conversionContext) { JsonElement value = extractFieldValue(hit.get("_source").getAsJsonObject(), absoluteName); if (value == null || value.isJsonNull()) { return null; }/*from w w w . j a v a2s . c om*/ // TODO: HSEARCH-2255 should we do it? if (!value.isJsonPrimitive()) { throw LOG.unsupportedProjectionOfNonJsonPrimitiveFields(value); } JsonPrimitive primitive = value.getAsJsonPrimitive(); if (primitive.isBoolean()) { return primitive.getAsBoolean(); } else if (primitive.isNumber()) { // TODO HSEARCH-2255 this will expose a Gson-specific Number implementation; Can we somehow return an Integer, // Long... etc. instead? return primitive.getAsNumber(); } else if (primitive.isString()) { return primitive.getAsString(); } else { // TODO HSEARCH-2255 Better raise an exception? return primitive.toString(); } }
From source file:org.hillview.storage.JsonFileLoader.java
License:Open Source License
void append(IAppendableColumn[] columns, JsonElement e) { if (!e.isJsonObject()) this.error("JSON array element is not a JsonObject"); JsonObject obj = e.getAsJsonObject(); for (IAppendableColumn col : columns) { JsonElement el = obj.get(col.getName()); if (el == null || el.isJsonNull()) { col.appendMissing();/*from w w w . j a v a 2 s . c o m*/ continue; } if (!el.isJsonPrimitive()) this.error("JSON array element is a non-primitive field"); JsonPrimitive prim = el.getAsJsonPrimitive(); if (prim.isBoolean()) { col.append(prim.getAsBoolean() ? "true" : "false"); } else if (prim.isNumber()) { col.append(prim.getAsDouble()); } else if (prim.isString()) { col.parseAndAppendString(prim.getAsString()); } else { this.error("Unexpected Json value" + prim.toString()); } } }
From source file:org.jsonddl.generator.InferSchema.java
License:Apache License
private Type inferType(String propertyName, JsonElement node) { if (node.isJsonPrimitive()) { JsonPrimitive p = node.getAsJsonPrimitive(); if (p.isBoolean()) { return new Type.Builder().withKind(Kind.BOOLEAN).build(); }/* w w w. j a va2 s .co m*/ if (p.isNumber()) { return new Type.Builder().withKind(Kind.DOUBLE).build(); } if (p.isString()) { return new Type.Builder().withKind(Kind.STRING).build(); } throw new RuntimeException("Unhandled primitive type " + p.toString()); } if (node.isJsonObject()) { JsonObject object = node.getAsJsonObject(); return inferFromObject(propertyName, object); } if (node.isJsonArray()) { return inferFromArray(propertyName, node.getAsJsonArray()); } throw new RuntimeException("Could not infer type from node " + node.toString()); }
From source file:org.qcert.runtime.UnaryOperators.java
License:Apache License
private static void tostring(StringBuilder sb, JsonPrimitive jp) { if (jp.isString()) { sb.append(jp.getAsString());// w w w .ja va2 s . c om } else { sb.append(jp.toString()); } }