List of usage examples for com.google.gson JsonObject entrySet
public Set<Map.Entry<String, JsonElement>> entrySet()
From source file:com.ibm.common.activitystreams.internal.MultimapAdapter.java
License:Apache License
/** * Method deserialize.//from ww w . jav a2 s. co m * @param json JsonElement * @param typeOfT Type * @param context JsonDeserializationContext * @return Multimap * @throws JsonParseException * @see com.google.gson.JsonDeserializer#deserialize(JsonElement, Type, JsonDeserializationContext) */ public Multimap deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { ImmutableMultimap.Builder mm = ImmutableMultimap.builder(); JsonObject obj = json.getAsJsonObject(); for (Map.Entry<String, JsonElement> entry : obj.entrySet()) { String key = entry.getKey(); JsonElement val = entry.getValue(); if (val.isJsonArray()) { for (JsonElement el : val.getAsJsonArray()) { if (el.isJsonArray()) mm.put(key, arraydes(el.getAsJsonArray(), context)); else if (el.isJsonObject()) mm.put(key, context.deserialize(el, ASObject.class)); else if (el.isJsonPrimitive()) mm.put(key, primConverter.convert(el.getAsJsonPrimitive())); } } else if (val.isJsonObject()) { mm.put(key, context.deserialize(val, ASObject.class)); } else if (val.isJsonPrimitive()) { mm.put(key, primConverter.convert(val.getAsJsonPrimitive())); } } return mm.build(); }
From source file:com.ibm.common.activitystreams.internal.NaturalLanguageValueAdapter.java
License:Apache License
/** * Method deserialize./*from ww w .j a v a 2s . co m*/ * @param element JsonElement * @param type1 Type * @param context JsonDeserializationContext * @return NLV * @throws JsonParseException * @see com.google.gson.JsonDeserializer#deserialize(JsonElement, Type, JsonDeserializationContext) */ public NLV deserialize(JsonElement element, Type type1, JsonDeserializationContext context) throws JsonParseException { checkArgument(element.isJsonPrimitive() || element.isJsonObject()); if (element.isJsonPrimitive()) { JsonPrimitive prim = element.getAsJsonPrimitive(); checkArgument(prim.isString()); return NLV.SimpleNLV.make(prim.getAsString()); } else { try { JsonObject obj = element.getAsJsonObject(); NLV.MapNLV.Builder builder = NLV.MapNLV.make(); for (Entry<String, JsonElement> entry : obj.entrySet()) builder.set(entry.getKey(), entry.getValue().getAsString()); return builder.get(); } catch (Throwable t) { throw new IllegalArgumentException(); } } }
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());/*from www . j a v a2s . c o m*/ 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.activitystreams.util.AbstractDictionaryObjectAdapter.java
License:Apache License
public X deserialize(JsonElement element, Type type1, JsonDeserializationContext context) throws JsonParseException { checkArgument(element.isJsonObject()); try {/* w w w. java 2s.c om*/ JsonObject obj = element.getAsJsonObject(); B builder = builder(); for (Entry<String, JsonElement> entry : obj.entrySet()) builder.set(entry.getKey(), context.<Y>deserialize(entry.getValue(), klass)); return builder.get(); } catch (Throwable t) { t.printStackTrace(); throw new IllegalArgumentException(); } }
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;/*from w w w . j a v a2 s .co 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.client.ServiceAccount.java
License:Open Source License
/** * Returns an instance of ServiceAccount from the VCAP_SERVICES environment * variable.//from ww w. j a va2s . c om * <p> * When <code>serviceInstanceName</code> is null, this method returns * a ServiceAccount for the first valid IBM Globlization Pipeline service instance. * If <code>serviceInstanceName</code> is not null, this method look up a * matching service entry, and returns a ServiceAccount for the matching entry. * If <code>serviceInstanceName</code> is not null and there is no match, * this method returns null. * * @param serviceName * The name of IBM Globalization Pipeline service. If null, * the first service with a name matching GP_SERVICE_NAME_PATTERN * will be used. * @param serviceInstanceName * The name of IBM Globalization Pipeline service instance, or null * designating the first available service instance. * @return An instance of ServiceAccount for the specified service instance * name, or null. */ private static ServiceAccount getInstanceByVcapServices(String serviceName, String serviceInstanceName) { Map<String, String> env = System.getenv(); String vcapServices = env.get("VCAP_SERVICES"); if (vcapServices == null) { return null; } try { JsonObject obj = new JsonParser().parse(vcapServices).getAsJsonObject(); // When service name is specified, // this method returns only a matching entry if (serviceName != null) { JsonElement elem = obj.get(serviceName); if (elem != null && elem.isJsonArray()) { return parseToServiceAccount(elem.getAsJsonArray(), serviceInstanceName); } } // Otherwise, lookup a valid entry with a name matching // the default pattern GP_SERVICE_NAME_PATTERN. for (Entry<String, JsonElement> entry : obj.entrySet()) { String name = entry.getKey(); JsonElement elem = entry.getValue(); if (elem.isJsonArray() && GP_SERVICE_NAME_PATTERN.matcher(name).matches()) { ServiceAccount account = parseToServiceAccount(elem.getAsJsonArray(), serviceInstanceName); if (account != null) { return account; } } } } catch (JsonParseException e) { // Fall through - will return null } return null; }
From source file:com.ibm.g11n.pipeline.resfilter.GlobalizeJsResource.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 a JSON object."); }/*from w w w . j ava2s .c o m*/ JsonObject root_obj = root.getAsJsonObject(); Set<Map.Entry<String, JsonElement>> root_elements = root_obj.entrySet(); if (root_elements.size() != 1) { throw new IllegalResourceFormatException( "Only one top level language tag element is allowed per file."); } Map.Entry<String, JsonElement> top_level = root_elements.iterator().next(); String language = top_level.getKey(); // We just hang on to the language tag as part of the bundle. // When doing an import, we can validate that the language tag matches what they // say they are importing. bundle.setLanguage(language); JsonElement language_obj = top_level.getValue(); if (!language_obj.isJsonObject()) { throw new IllegalResourceFormatException("The top level language element is not a JSON object."); } addBundleStrings(language_obj.getAsJsonObject(), "", bundle, 0); } catch (JsonParseException e) { throw new IllegalResourceFormatException("Failed to parse the specified JSON contents.", e); } return bundle; }
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.// ww w .j a va 2 s . co m */ @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
@Override public LanguageBundle parse(InputStream inStream, FilterOptions options) throws IOException, ResourceFilterException { LanguageBundleBuilder bb = new LanguageBundleBuilder(false); // TODO: can we use auto sequence# mode? 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 a JSON object."); }//from w w w . j a v a 2s . c om JsonObject root_obj = root.getAsJsonObject(); Set<Map.Entry<String, JsonElement>> root_elements = root_obj.entrySet(); if (root_elements.size() != 1) { throw new IllegalResourceFormatException( "Only one top level language tag element is allowed per file."); } Map.Entry<String, JsonElement> top_level = root_elements.iterator().next(); String language = top_level.getKey(); // We just hang on to the language tag as part of the bundle. // When doing an import, we can validate that the language tag matches what they // say they are importing. bb.embeddedLanguageCode(language); JsonElement language_obj = top_level.getValue(); if (!language_obj.isJsonObject()) { throw new IllegalResourceFormatException("The top level language element is not a JSON object."); } addBundleStrings(language_obj.getAsJsonObject(), "", bb, 0); } catch (JsonParseException e) { throw new IllegalResourceFormatException("Failed to parse the specified JSON contents.", e); } return bb.build(); }
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 . ja v a 2s . c o 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; }