Example usage for com.google.gson JsonElement getAsJsonPrimitive

List of usage examples for com.google.gson JsonElement getAsJsonPrimitive

Introduction

In this page you can find the example usage for com.google.gson JsonElement getAsJsonPrimitive.

Prototype

public JsonPrimitive getAsJsonPrimitive() 

Source Link

Document

convenience method to get this element as a JsonPrimitive .

Usage

From source file:com.ibm.common.activitystreams.internal.TypeValueAdapter.java

License:Apache License

/**
 * Method deserialize.//from  w w w .  j a  v a 2s.  c  o  m
 * @param el JsonElement
 * @param type Type
 * @param context JsonDeserializationContext
        
        
        
 * @return TypeValue * @throws JsonParseException * @see com.google.gson.JsonDeserializer#deserialize(JsonElement, Type, JsonDeserializationContext) */
public TypeValue deserialize(JsonElement el, Type type, JsonDeserializationContext context)
        throws JsonParseException {
    checkArgument(el.isJsonPrimitive() || el.isJsonObject());
    if (el.isJsonPrimitive()) {
        JsonPrimitive prim = el.getAsJsonPrimitive();
        checkArgument(prim.isString());
        return type(prim.getAsString());
    } else {
        JsonObject obj = el.getAsJsonObject();
        if (obj.has("objectType")) {
            TypeValue tv = context.deserialize(obj.get("objectType"), TypeValue.class);
            Model pMap = schema.forObjectType(tv.id());
            return context.<ASObject>deserialize(el, pMap.type() != null ? pMap.type() : ASObject.class);
        } else {
            return context.<ASObject>deserialize(el, ASObject.class);
        }
    }
}

From source file:com.ibm.common.activitystreams.legacy.MediaLinkAdapter.java

License:Apache License

public MediaLink deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {

    checkArgument(json.isJsonObject());// ww  w.j a va  2s.  com
    JsonObject obj = (JsonObject) json;
    MediaLink.Builder builder = LegacyMakers.mediaLink();
    for (Map.Entry<String, JsonElement> entry : obj.entrySet()) {
        String name = entry.getKey();
        JsonElement val = entry.getValue();
        if (val.isJsonPrimitive())
            builder.set(name, primConverter.convert(val.getAsJsonPrimitive()));
        else if (val.isJsonArray())
            builder.set(name, context.deserialize(val, Iterable.class));
        else if (val.isJsonObject())
            builder.set(name, context.deserialize(val, ASObject.class));
    }
    return builder.get();
}

From source file:com.ibm.common.geojson.as2.GeoAdapter.java

License:Apache License

@Override
public GeoObject deserialize(JsonElement element, Type type, JsonDeserializationContext context)
        throws JsonParseException {
    GeoObject.Builder geo = null;//w  ww  .  ja v a2s.  c  o  m
    checkArgument(element.isJsonObject());
    JsonObject obj = element.getAsJsonObject();
    checkArgument(obj.has("type"));
    GeoObject.Type et = Enums.getIfPresent(GeoObject.Type.class, obj.get("type").getAsString().toUpperCase())
            .orNull();
    checkArgument(et != null);
    switch (et) {
    case FEATURE:
        geo = GeoMakers.feature();
        break;
    case FEATURECOLLECTION:
        geo = GeoMakers.featureCollection();
        type = Feature.class;
        break;
    case GEOMETRYCOLLECTION:
        geo = GeoMakers.geometryCollection();
        type = Geometry.class;
        break;
    case LINESTRING:
        geo = GeoMakers.linestring();
        type = Position.class;
        break;
    case MULTILINESTRING:
        geo = GeoMakers.multiLineString();
        type = LineString.class;
        break;
    case MULTIPOINT:
        geo = GeoMakers.multipoint();
        type = Position.class;
        break;
    case MULTIPOLYGON:
        geo = GeoMakers.multiPolygon();
        type = Polygon.class;
        break;
    case POINT:
        geo = GeoMakers.point();
        type = null;
        break;
    case POLYGON:
        geo = GeoMakers.polygon();
        type = LineString.class;
        break;
    }

    for (Map.Entry<String, JsonElement> entry : obj.entrySet()) {
        JsonElement el = entry.getValue();
        String name = entry.getKey();
        if ("crs".equals(name)) {
            CRS.Builder cb = new CRS.Builder();
            JsonObject o = el.getAsJsonObject();
            if (o.has("type"))
                cb.type(o.get("type").getAsString());
            if (o.has("properties")) {
                JsonObject p = o.get("properties").getAsJsonObject();
                for (Map.Entry<String, JsonElement> e : p.entrySet()) {
                    cb.set(e.getKey(), context.deserialize(e.getValue(), Object.class));
                }
            }
            geo.crs(cb.get());
        } else if ("properties".equals(name)) {
            geo.set("properties", context.deserialize(el, Map.class));
        } else if ("bbox".equals(name)) {
            BoundingBox.Builder bb = new BoundingBox.Builder();
            float[] points = context.deserialize(el, float[].class);
            bb.add(points);
            geo.boundingBox(bb.get());
        } else if ("features".equals(name)) {
            Feature[] features = context.deserialize(el, Feature[].class);
            FeatureCollection.Builder fcb = (FeatureCollection.Builder) geo;
            for (Feature f : features)
                fcb.add(f);
        } else if ("coordinates".equals(name)) {
            switch (et) {
            case LINESTRING: {
                LineString.Builder lsb = (LineString.Builder) geo;
                float[][] positions = context.deserialize(el, float[][].class);
                boolean ring = ring(positions);
                if (ring)
                    lsb.linearRing();
                for (int n = 0; n < positions.length; n++) {
                    if (!ring || (ring && n < positions.length - 1))
                        lsb.add(toPosition(positions[n]));
                }
                break;
            }
            case MULTIPOINT: {
                MultiPoint.Builder lsb = (MultiPoint.Builder) geo;
                float[][] positions = context.deserialize(el, float[][].class);
                for (float[] pos : positions)
                    lsb.add(toPosition(pos));
                break;
            }
            case MULTILINESTRING: {
                MultiLineString.Builder mlb = (MultiLineString.Builder) geo;
                float[][][] positions = context.deserialize(el, float[][][].class);
                for (float[][] lines : positions) {
                    LineString.Builder lsb = GeoMakers.linestring();
                    boolean ring = ring(lines);
                    if (ring)
                        lsb.linearRing();
                    for (int n = 0; n < lines.length; n++) {
                        if (!ring || (ring && n < lines.length - 1))
                            lsb.add(toPosition(lines[n]));
                    }
                    for (float[] pos : lines)
                        lsb.add(toPosition(pos));
                    mlb.add(lsb);
                }
                break;
            }
            case POLYGON: {
                Polygon.Builder mlb = (Polygon.Builder) geo;
                float[][][] positions = context.deserialize(el, float[][][].class);
                for (float[][] lines : positions) {
                    LineString.Builder lsb = GeoMakers.linestring();
                    for (float[] pos : lines)
                        lsb.add(toPosition(pos));
                    mlb.add(lsb);
                }
                break;
            }
            case MULTIPOLYGON: {
                MultiPolygon.Builder mpb = (MultiPolygon.Builder) geo;
                float[][][][] positions = context.deserialize(el, float[][][][].class);
                for (float[][][] polygons : positions) {
                    Polygon.Builder pb = GeoMakers.polygon();
                    for (float[][] lines : polygons) {
                        LineString.Builder lsb = GeoMakers.linestring();
                        for (float[] pos : lines)
                            lsb.add(toPosition(pos));
                        pb.add(lsb);
                    }
                    mpb.add(pb);
                }
                break;
            }
            case POINT:
                Point.Builder pb = (Point.Builder) geo;
                float[] position = context.deserialize(el, float[].class);
                pb.position(toPosition(position));
                break;
            default:
                break;
            }
        } else if ("geometries".equals(name)) {
            Geometry[] geos = context.deserialize(el, Geometry[].class);
            GeometryCollection.Builder fcb = (GeometryCollection.Builder) geo;
            for (Geometry<?, ?> g : geos)
                fcb.add(g);
        } else {
            if (el.isJsonArray()) {
                geo.set(name, context.deserialize(el, Object.class));
            } else if (el.isJsonObject()) {
                geo.set(name, context.deserialize(el, GeoObject.class));
            } else if (el.isJsonPrimitive()) {
                JsonPrimitive p = el.getAsJsonPrimitive();
                if (p.isBoolean())
                    geo.set(name, p.getAsBoolean());
                else if (p.isNumber())
                    geo.set(name, p.getAsNumber());
                else if (p.isString())
                    geo.set(name, p.getAsString());
            }
        }
    }

    return geo.get();
}

From source file:com.ibm.g11n.pipeline.resfilter.GlobalizeJsResource.java

License:Open Source License

/**
 * The override of addBundleStrings is necessary because globalizejs treats arrays of strings
 * as a single long string, with each piece separated by a space, rather than treating it like
 * a real JSON array./*from  w w w  .  j  a  v  a2  s . c om*/
 */
@Override
protected int addBundleStrings(JsonObject obj, String keyPrefix, Bundle bundle, int sequenceNum) {
    for (Map.Entry<String, JsonElement> entry : obj.entrySet()) {
        String key = entry.getKey();
        JsonElement value = entry.getValue();
        if (value.isJsonObject()) {
            sequenceNum = addBundleStrings(value.getAsJsonObject(), encodeResourceKey(keyPrefix, key, false),
                    bundle, sequenceNum);
        } else if (value.isJsonArray()) {
            JsonArray ar = value.getAsJsonArray();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < ar.size(); i++) {
                JsonElement arrayEntry = ar.get(i);
                if (arrayEntry.isJsonPrimitive() && arrayEntry.getAsJsonPrimitive().isString()) {
                    if (i > 0) {
                        sb.append(" "); //
                    }
                    sb.append(arrayEntry.getAsString());
                } else {
                    throw new IllegalResourceFormatException(
                            "Arrays must contain only strings in a globalizejs resource.");
                }
            }
            sequenceNum++;
            bundle.addResourceString(encodeResourceKey(keyPrefix, key, true), sb.toString(), sequenceNum);
        } else if (!value.isJsonPrimitive() || !value.getAsJsonPrimitive().isString()) {
            throw new IllegalResourceFormatException("The value of JSON element " + key + " is not a string.");
        } else {
            sequenceNum++;
            bundle.addResourceString(encodeResourceKey(keyPrefix, key, true), value.getAsString(), sequenceNum);
        }
    }
    return sequenceNum;
}

From source file:com.ibm.g11n.pipeline.resfilter.impl.GlobalizeJsResource.java

License:Open Source License

/**
 * The override of addBundleStrings is necessary because globalizejs treats arrays of strings
 * as a single long string, with each piece separated by a space, rather than treating it like
 * a real JSON array.//w  w  w  .  jav a2  s .  co  m
 */
@Override
protected int addBundleStrings(JsonObject obj, String keyPrefix, LanguageBundleBuilder bb, int sequenceNum)
        throws ResourceFilterException {
    for (Map.Entry<String, JsonElement> entry : obj.entrySet()) {
        String key = entry.getKey();
        JsonElement value = entry.getValue();
        if (value.isJsonObject()) {
            sequenceNum = addBundleStrings(value.getAsJsonObject(), encodeResourceKey(keyPrefix, key, false),
                    bb, sequenceNum);
        } else if (value.isJsonArray()) {
            JsonArray ar = value.getAsJsonArray();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < ar.size(); i++) {
                JsonElement arrayEntry = ar.get(i);
                if (arrayEntry.isJsonPrimitive() && arrayEntry.getAsJsonPrimitive().isString()) {
                    if (i > 0) {
                        sb.append(" "); //
                    }
                    sb.append(arrayEntry.getAsString());
                } else {
                    throw new IllegalResourceFormatException(
                            "Arrays must contain only strings in a globalizejs resource.");
                }
            }
            sequenceNum++;
            bb.addResourceString(encodeResourceKey(keyPrefix, key, true), sb.toString(), sequenceNum);
        } else if (!value.isJsonPrimitive() || !value.getAsJsonPrimitive().isString()) {
            throw new IllegalResourceFormatException("The value of JSON element " + key + " is not a string.");
        } else {
            sequenceNum++;
            bb.addResourceString(encodeResourceKey(keyPrefix, key, true), value.getAsString(), sequenceNum);
        }
    }
    return sequenceNum;
}

From source file:com.ibm.g11n.pipeline.resfilter.impl.JsonResource.java

License:Open Source License

protected int addBundleStrings(JsonObject obj, String keyPrefix, LanguageBundleBuilder bb, int sequenceNum)
        throws ResourceFilterException {
    for (Map.Entry<String, JsonElement> entry : obj.entrySet()) {
        String key = entry.getKey();
        JsonElement value = entry.getValue();
        if (value.isJsonObject()) {
            sequenceNum = addBundleStrings(value.getAsJsonObject(), encodeResourceKey(keyPrefix, key, false),
                    bb, sequenceNum);/*  ww w  .ja  va  2s  .  c om*/
        } else if (value.isJsonArray()) {
            JsonArray ar = value.getAsJsonArray();
            for (int i = 0; i < ar.size(); i++) {
                JsonElement arrayEntry = ar.get(i);
                String arrayKey = encodeResourceKey(keyPrefix, key, false) + "[" + Integer.toString(i) + "]";
                if (arrayEntry.isJsonPrimitive() && arrayEntry.getAsJsonPrimitive().isString()) {
                    sequenceNum++;
                    bb.addResourceString(ResourceString.with(arrayKey, arrayEntry.getAsString())
                            .sequenceNumber(sequenceNum));
                } else {
                    sequenceNum = addBundleStrings(arrayEntry.getAsJsonObject(), arrayKey, bb, sequenceNum);
                }
            }
        } else if (!value.isJsonPrimitive() || !value.getAsJsonPrimitive().isString()) {
            throw new IllegalResourceFormatException("The value of JSON element " + key + " is not a string.");
        } else {
            sequenceNum++;
            bb.addResourceString(
                    ResourceString.with(encodeResourceKey(keyPrefix, key, true), value.getAsString())
                            .sequenceNumber(sequenceNum));
        }
    }
    return sequenceNum;
}

From source file:com.ibm.g11n.pipeline.resfilter.JsonResource.java

License:Open Source License

@Override
public Bundle parse(InputStream inStream) throws IOException {
    Bundle bundle = new Bundle();
    try (InputStreamReader reader = new InputStreamReader(new BomInputStream(inStream),
            StandardCharsets.UTF_8)) {
        JsonElement root = new JsonParser().parse(reader);
        if (!root.isJsonObject()) {
            throw new IllegalResourceFormatException("The root JSON element is not an JSON object.");
        }/* w w  w.j a  va 2s .com*/
        int sequenceNum = 0;
        for (Map.Entry<String, JsonElement> entry : root.getAsJsonObject().entrySet()) {
            String key = entry.getKey();
            JsonElement value = entry.getValue();
            if (!value.isJsonPrimitive() || !value.getAsJsonPrimitive().isString()) {
                throw new IllegalResourceFormatException(
                        "The value of JSON element " + key + " is not a string.");
            }
            sequenceNum++;
            bundle.addResourceString(key, value.getAsString(), sequenceNum);
        }
    } catch (JsonParseException e) {
        throw new IllegalResourceFormatException("Failed to parse the specified JSON contents.", e);
    }
    return bundle;
}

From source file:com.ibm.streamsx.topology.generator.spl.SPLGenerator.java

License:Open Source License

/**
 * Add an arbitrary SPL value./*from www. ja  va2s  .c o  m*/
 * JsonObject has a type and a value. 
 */
static void value(StringBuilder sb, JsonObject tv) {

    JsonElement value = tv.get("value");

    String type = JParamTypes.TYPE_SPL_EXPRESSION;
    if (tv.has("type")) {
        type = tv.get("type").getAsString();
    } else {
        if (value.isJsonPrimitive()) {
            JsonPrimitive pv = value.getAsJsonPrimitive();
            if (pv.isString())
                type = "RSTRING";
        } else if (value.isJsonArray()) {
            type = "RSTRING";
        }
    }

    if (value.isJsonArray()) {
        JsonArray array = value.getAsJsonArray();

        for (int i = 0; i < array.size(); i++) {
            if (i != 0)
                sb.append(", ");
            value(sb, type, array.get(i));
        }
    } else {
        value(sb, type, value);
    }
}

From source file:com.ibm.streamsx.topology.generator.spl.SPLGenerator.java

License:Open Source License

/**
 * Add a single value of a known type./*from w  ww  .  j  av a  2s.co m*/
 */
static void value(StringBuilder sb, String type, JsonElement value) {
    switch (type) {
    case "UINT8":
    case "UINT16":
    case "UINT32":
    case "UINT64":
    case "INT8":
    case "INT16":
    case "INT32":
    case "INT64":
    case "FLOAT32":
    case "FLOAT64":
        numberLiteral(sb, value.getAsJsonPrimitive(), type);
        break;
    case "RSTRING":
        stringLiteral(sb, value.getAsString());
        break;
    case "USTRING":
        stringLiteral(sb, value.getAsString());
        sb.append("u");
        break;

    case "BOOLEAN":
        sb.append(value.getAsBoolean());
        break;

    default:
    case JParamTypes.TYPE_ENUM:
    case JParamTypes.TYPE_SPLTYPE:
    case JParamTypes.TYPE_ATTRIBUTE:
    case JParamTypes.TYPE_SPL_EXPRESSION:
        sb.append(value.getAsString());
        break;
    }
}

From source file:com.ibm.watson.developer_cloud.util.DateDeserializer.java

License:Open Source License

@Override
public synchronized Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {

    if (json.isJsonNull() || json.getAsString().isEmpty()) {
        return null;
    }/* w  w  w . jav a2s  .c o  m*/

    String dateAsString = json.getAsJsonPrimitive().getAsString().replaceAll("Z$", "+0000");
    ParseException e = null;

    for (SimpleDateFormat format : dateFormatters) {
        try {
            return format.parse(dateAsString);
        } catch (ParseException e1) {
            e = e1;
        }
    }

    Pattern isJustNumber = Pattern.compile("^\\d+$");
    Matcher foundMatch = isJustNumber.matcher(dateAsString);
    if (foundMatch.find()) {
        Long timeAsLong = Long.parseLong(dateAsString);
        Long msCheck = 100000000000L;

        // are we ms or seconds maybe?
        if (timeAsLong < msCheck) {
            // assuming in seconds
            timeAsLong = timeAsLong * 1000;
        }
        return new Date(timeAsLong);
    }

    LOG.log(Level.SEVERE, "Error parsing: " + dateAsString, e);
    return null;
}