Example usage for com.google.gson JsonObject entrySet

List of usage examples for com.google.gson JsonObject entrySet

Introduction

In this page you can find the example usage for com.google.gson JsonObject entrySet.

Prototype

public Set<Map.Entry<String, JsonElement>> entrySet() 

Source Link

Document

Returns a set of members of this object.

Usage

From source file:com.pigtail.jsoncsvconverter.JsonReader.java

public static void processJson(JsonObject json) {
    for (Map.Entry<?, ?> entry : json.entrySet()) {
        String key = entry.getKey().toString();
        HashSet locations = new HashSet<Integer>();
        JsonArray value = (JsonArray) entry.getValue();
        for (JsonElement element : value) {
            int index = headers.indexOf(element.getAsString());
            if (index == -1) {
                headers.add(element.getAsString());
                index = headers.indexOf(element.getAsString());
            }/* w  ww.j  a va 2s. com*/
            locations.add(index);
            data.put(key, locations);
        }
        System.out.println(key + "" + value);
    }
}

From source file:com.pmeade.arya.gson.deserialize.ParameterizedFieldDeserializer.java

License:Open Source License

/**
 * Deserialize a JSON object into a Map object.
 * @param jo JSON data wrapped in Gson's JsonObject
 * @param type type of the Map object//  ww w  .j  a v a 2s .c  o  m
 * @return Map containing the deserialized JSON object
 */
private Object deserializeMap(JsonObject jo, Type type) {
    // obtain the raw parameterized type (i.e.: Map, SortedMap, etc.)
    ParameterizedType paraType = (ParameterizedType) type;
    Class rawType = (Class) paraType.getRawType();
    // reference to the map that we will create below
    Map map = null;
    // if the map type is an interface
    if (rawType.isInterface()) {
        //  then we need to come up with a matching concrete implementation
        if (Map.class.equals(rawType)) {
            map = new HashMap();
        } else if (NavigableMap.class.equals(rawType)) {
            map = new TreeMap();
        } else if (SortedMap.class.equals(rawType)) {
            map = new TreeMap();
        } else {
            // we don't know what kind of map this is, so we don't know
            // what concrete implementation to provide
            throw new UnsupportedOperationException();
        }
    }
    // otherwise we just need one of whatever this thing is expecting
    else {
        try {
            // attempt to instantiate the provided concrete type 
            map = (Map) rawType.newInstance();
        } catch (Exception e) {
            // if we failed at that, fall back to a HashMap
            log.error("Unable to create type " + rawType + ":", e);
            map = new HashMap();
        }
    }
    // now, determine the actual type of the things in the map
    // that is: Map<K,V> .. what type are K and V?
    Type[] actualTypes = paraType.getActualTypeArguments();
    // if the value type (V) is also a parameterized type (i.e.: a Map
    // or Collection in it's own right; e.g.: Map<String,List<Integer>>)
    if (actualTypes[1] instanceof ParameterizedType) {
        // determine the raw parameterized type of the thing in the
        // value side of the map (i.e.: is it a Collection or a Map?)
        Class keyType = (Class) actualTypes[0];
        ParameterizedType innerParaType = (ParameterizedType) actualTypes[1];
        Class innerRawType = (Class) innerParaType.getRawType();
        // for each entry in the provided JsonObject data
        for (Entry<String, JsonElement> entry : jo.entrySet()) {
            // obtain the object that corresponds to the key part of the map
            Object key = toMapKey(entry.getKey(), keyType);
            // a reference to the value part of the map that we'll create below
            Object value = null;
            // if the inner value type is assignable to Collection
            if (Collection.class.isAssignableFrom(innerRawType)) {
                // deserialize the value side as a Collection object
                value = deserializeCollection(entry.getValue().getAsJsonArray(), innerParaType);
            }
            // otheerwise, if the inner value type is assignable to Map
            else if (Map.class.isAssignableFrom(innerRawType)) {
                // deserialize the value side as a Map object
                value = deserializeMap(entry.getValue().getAsJsonObject(), innerParaType);
            } else {
                // otherwise, we don't know what kind of parameterized
                // type this represents...
                throw new UnsupportedOperationException();
            }
            // once we've obtained both key and value, populate the map
            map.put(key, value);
        }
    }
    // TODO: Add else-if case here to handle inner array types. This would
    //       add support for cases like List<Boolean[]> or Set<double[][]>
    //
    //        else if(actualTypes[0] is Array of some type) { blah }
    // otherwise, the value side is not a parameterized type
    else {
        // determine the actual types of the key and value of the map
        Class keyType = (Class) actualTypes[0];
        Class valueType = (Class) actualTypes[1];
        // for each entry in the provided JsonObject data
        for (Entry<String, JsonElement> entry : jo.entrySet()) {
            // convert the key side (String) to an object of the key type
            Object key = toMapKey(entry.getKey(), keyType);
            // convert the value side (JsonElement) to an object of the
            // value type
            Object value = toMapValue(entry.getValue(), valueType);
            // once we've obtained both key and value, populate the map
            map.put(key, value);
        }
    }
    // return the completed map to the caller
    return map;
}

From source file:com.pptv.sp.flume.sink.elasticsearch.ElasticSearchJsonLogStashEventSerializer.java

License:Apache License

private void appendBody(XContentBuilder builder, Event event) throws IOException, UnsupportedEncodingException {
    String body = new String(event.getBody());
    JsonParser parser = new JsonParser();
    JsonObject jsonObj = parser.parse(body).getAsJsonObject();
    for (Entry<String, JsonElement> kv : jsonObj.entrySet()) {
        ContentBuilderUtil.appendField(builder, kv.getKey(), kv.getValue().getAsString().getBytes());
        //kv.getValue().getAsByte();
    }/* www.  ja v  a  2  s.  co  m*/
    //ContentBuilderUtil.appendField(builder, "@message", body);
}

From source file:com.prayer.vakit.times.gson.RuntimeTypeAdapterFactory.java

License:Apache License

@Override
public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (type.getRawType() != baseType) {
        return null;
    }//from   w w  w.j a  va2 s. c  o  m

    final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<>();
    final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<>();
    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>() {
        @Override
        public R read(JsonReader in) throws IOException {
            JsonElement jsonElement = Streams.parse(in);
            JsonElement labelJsonElement = jsonElement.getAsJsonObject().remove(typeFieldName);
            if (labelJsonElement == null) {
                throw new JsonParseException("cannot deserialize " + baseType
                        + " because it does not define a field named " + typeFieldName);
            }
            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);
            }
            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.qmetry.qaf.automation.gson.GsonObjectDeserializer.java

License:Open Source License

public static Object read(JsonElement in) {

    if (in.isJsonArray()) {
        List<Object> list = new ArrayList<Object>();
        JsonArray arr = in.getAsJsonArray();
        for (JsonElement anArr : arr) {
            list.add(read(anArr));/*from  w ww.ja v  a 2  s . c o m*/
        }
        return list;
    } else if (in.isJsonObject()) {
        Map<String, Object> map = new LinkedTreeMap<String, Object>();
        JsonObject obj = in.getAsJsonObject();
        Set<Map.Entry<String, JsonElement>> entitySet = obj.entrySet();
        for (Map.Entry<String, JsonElement> entry : entitySet) {
            map.put(entry.getKey(), read(entry.getValue()));
        }
        return map;
    } else if (in.isJsonPrimitive()) {
        JsonPrimitive prim = in.getAsJsonPrimitive();
        if (prim.isBoolean()) {
            return prim.getAsBoolean();
        } else if (prim.isString()) {
            return prim.getAsString();
        } else if (prim.isNumber()) {
            if (prim.getAsString().contains("."))
                return prim.getAsDouble();
            else {
                return prim.getAsLong();
            }
        }
    }
    return null;
}

From source file:com.redhat.thermostat.gateway.service.commands.channel.coders.typeadapters.BasicMessageTypeAdapter.java

License:Open Source License

private SortedMap<String, String> decodePayloadAsParamMap(JsonObject payloadElem) {
    SortedMap<String, String> paramMap = new TreeMap<>();
    if (payloadElem == null) {
        return paramMap; // no params
    }//from   w  w w  .ja  va2s . c  o m
    for (Entry<String, JsonElement> entry : payloadElem.entrySet()) {
        JsonElement value = entry.getValue();
        String strValue = null;
        if (value != null && !value.isJsonNull()) {
            strValue = value.getAsString();
        }
        paramMap.put(entry.getKey(), strValue);
    }
    return paramMap;
}

From source file:com.replaymod.replaystudio.replay.AbstractReplayFile.java

License:MIT License

@Override
public Map<Integer, String> getResourcePackIndex() throws IOException {
    Optional<InputStream> in = get(ENTRY_RESOURCE_PACK_INDEX);
    if (!in.isPresent()) {
        return null;
    }/*from w w w  . j av a2  s  . c  o m*/
    Map<Integer, String> index = new HashMap<>();
    try (Reader is = new InputStreamReader(in.get())) {
        JsonObject array = new Gson().fromJson(is, JsonObject.class);
        for (Map.Entry<String, JsonElement> e : array.entrySet()) {
            try {
                index.put(Integer.parseInt(e.getKey()), e.getValue().getAsString());
            } catch (NumberFormatException ignored) {
            }
        }
    }
    return index;
}

From source file:com.rest.samples.GetJSON.java

public static void main(String[] args) {
    // TODO code application logic here
    //        String url = "https://api.adorable.io/avatars/list";
    String url = "http://freemusicarchive.org/api/get/albums.json?api_key=60BLHNQCAOUFPIBZ&limit=5";
    try {//from w ww.jav a2s  .  c o m
        HttpClient hc = HttpClientBuilder.create().build();
        HttpGet getMethod = new HttpGet(url);
        getMethod.addHeader("accept", "application/json");
        HttpResponse res = hc.execute(getMethod);
        if (res.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("Failed : HTTP eror code: " + res.getStatusLine().getStatusCode());
        }

        InputStream is = res.getEntity().getContent();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        JsonParser parser = new JsonParser();
        JsonElement element = parser.parse(br);
        if (element.isJsonObject()) {
            JsonObject jsonObject = element.getAsJsonObject();
            Set<Map.Entry<String, JsonElement>> jsonEntrySet = jsonObject.entrySet();
            for (Map.Entry<String, JsonElement> entry : jsonEntrySet) {
                if (entry.getValue().isJsonArray() && entry.getValue().getAsJsonArray().size() > 0) {
                    JsonArray jsonArray = entry.getValue().getAsJsonArray();
                    Set<Map.Entry<String, JsonElement>> internalJsonEntrySet = jsonArray.get(0)
                            .getAsJsonObject().entrySet();
                    for (Map.Entry<String, JsonElement> entrie : internalJsonEntrySet) {
                        System.out.println("--->   " + entrie.getKey() + " --> " + entrie.getValue());

                    }

                } else {
                    System.out.println(entry.getKey() + " --> " + entry.getValue());
                }
            }
        }

        String output;
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }

    } catch (IOException ex) {
        Logger.getLogger(SamplesUseHttpclient.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.ryanantkowiak.jOptionsHouseAPI.JsonUtilities.java

License:Open Source License

/**
 * Recursively print the contents of a GSON JSON element.
 * //from   w ww.j  a  v a 2 s.  c o m
 * @param element   the GSON JSON element to be printed
 * @param prefix   output will be prefixed with this string
 */
public static void printJson(JsonElement element, String prefix) {
    if (null == prefix || prefix.isEmpty()) {
        prefix = "";
    }

    if (null == element || element.isJsonNull()) {
        System.out.println(prefix + " [null]");
        return;
    }

    else if (element.isJsonPrimitive()) {
        JsonPrimitive p = element.getAsJsonPrimitive();
        if (p.isBoolean()) {
            System.out.println(prefix + " [bool=" + p.getAsBoolean() + "]");
        } else if (p.isString()) {
            System.out.println(prefix + " [string='" + p.getAsString() + "']");
        } else if (p.isNumber()) {
            System.out.println(prefix + " [number=" + p.getAsDouble() + "]");
        }
    }

    else if (element.isJsonArray()) {
        System.out.println(prefix + " [array]");
        for (int i = 0; i < element.getAsJsonArray().size(); ++i) {
            String newPrefix = prefix + "[" + i + "]";
            printJson(element.getAsJsonArray().get(i), newPrefix);
        }
    }

    else if (element.isJsonObject()) {
        JsonObject obj = element.getAsJsonObject();

        for (Map.Entry<String, JsonElement> entry : obj.entrySet()) {
            String key = entry.getKey();
            JsonElement value = entry.getValue();
            String newPrefix = prefix + "." + key;
            printJson(value, newPrefix);
        }
    }

}

From source file:com.samsung.memoryanalysis.traceparser.TraceAnalysisRunner.java

License:Open Source License

private FreeVariables buildFVMap(File dir) throws IOException {
    File fvFile = new File(dir, "freevars.json");
    FreeVariables res = new FreeVariables();
    if (fvFile.exists()) {
        JsonObject json = null;
        try {//from w ww .j a va  2 s .c o  m
            json = parser.parse(new BufferedReader(new FileReader(fvFile))).getAsJsonObject();// parser.parse(js.get());
        } catch (JsonParseException ex) {
            throw new IOException("Invalid free-variables map file: " + ex.getMessage());
        }

        for (Map.Entry<String, JsonElement> entry : json.entrySet()) {
            JsonElement o = entry.getValue();
            if (o.isJsonPrimitive() && o.getAsJsonPrimitive().isString())
                res.put(Integer.parseInt(entry.getKey()), FreeVariables.ANY);
            else {
                JsonArray a = o.getAsJsonArray();
                final Set<String> freeVars = HashSetFactory.make();
                for (int i = 0; i < a.size(); i++) {
                    final JsonElement jsonElement = a.get(i);
                    freeVars.add(jsonElement.getAsString());
                }
                res.put(Integer.parseInt(entry.getKey()), freeVars);
            }
        }
    }
    return res;
}