Example usage for com.google.gson JsonElement getAsJsonObject

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

Introduction

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

Prototype

public JsonObject getAsJsonObject() 

Source Link

Document

convenience method to get this element as a JsonObject .

Usage

From source file:com.balajeetm.mystique.util.gson.lever.JsonLever.java

License:Open Source License

/**
 * A recursive merge of two json elements.
 *
 * @param source1 the first json element
 * @param source2 the second json element
 * @param mergeArray the flag to denote if arrays should be merged
 * @return the recursively merged json element
 *///w ww .j a va2  s. c o m
public JsonElement merge(JsonElement source1, JsonElement source2, Boolean mergeArray) {
    mergeArray = null == mergeArray ? Boolean.FALSE : mergeArray;
    JsonElement result = JsonNull.INSTANCE;
    source1 = asJsonElement(source1, JsonNull.INSTANCE);
    source2 = asJsonElement(source2, JsonNull.INSTANCE);
    if (source1.getClass().equals(source2.getClass())) {
        if (source1.isJsonObject()) {
            JsonObject obj1 = asJsonObject(source1);
            JsonObject obj2 = asJsonObject(source2);
            result = obj1;
            JsonObject resultObj = result.getAsJsonObject();
            for (Entry<String, JsonElement> entry : obj1.entrySet()) {
                String key = entry.getKey();
                JsonElement value1 = entry.getValue();
                JsonElement value2 = obj2.get(key);
                JsonElement merge = merge(value1, value2, mergeArray);
                resultObj.add(key, merge);
            }
            for (Entry<String, JsonElement> entry : obj2.entrySet()) {
                String key = entry.getKey();
                if (!resultObj.has(key)) {
                    resultObj.add(key, entry.getValue());
                }
            }
        } else if (source1.isJsonArray()) {
            result = new JsonArray();
            JsonArray resultArray = result.getAsJsonArray();
            JsonArray array1 = asJsonArray(source1);
            JsonArray array2 = asJsonArray(source2);
            int index = 0;
            int a1size = array1.size();
            int a2size = array2.size();

            if (!mergeArray) {
                for (; index < a1size && index < a2size; index++) {
                    resultArray.add(merge(array1.get(index), array2.get(index), mergeArray));
                }
            }

            for (; index < a1size; index++) {
                resultArray.add(array1.get(index));
            }

            index = mergeArray ? 0 : index;

            for (; index < a2size; index++) {
                resultArray.add(array2.get(index));
            }

        } else {
            result = source1 != null ? source1 : source2;
        }
    } else {
        result = isNotNull(source1) ? source1 : source2;
    }
    return result;
}

From source file:com.balajeetm.mystique.util.gson.lever.JsonLever.java

License:Open Source License

/**
 * Gets the replete field.// w w w.  ja v  a 2s .  c o  m
 *
 * @param field the field
 * @param path the path
 * @param nextPath the next path
 * @return the replete field
 */
protected JsonElement getRepleteField(JsonElement field, JsonElement path, JsonElement nextPath) {
    if (isNumber(path)) {
        Integer index = path.getAsInt();
        if (!isArray(field)) {
            field = new JsonArray();
        }
        JsonArray fArray = repleteArray(field.getAsJsonArray(), index,
                isNumber(nextPath) ? JsonArray.class : JsonObject.class);
        field = fArray;
    } else {
        String fieldName = path.getAsString();
        if (!isObject(field)) {
            field = new JsonObject();
        }
        JsonObject fJson = repleteJson(field.getAsJsonObject(), fieldName,
                isNumber(nextPath) ? JsonArray.class : JsonObject.class);
        field = fJson;
    }
    return field;
}

From source file:com.balajeetm.mystique.util.gson.lever.JsonQuery.java

License:Open Source License

public Flux<JsonElement> queryAsync(JsonObject query) {
    return Flux.just(query).map(q -> validate(q)).flatMap(s -> {
        Flux<JsonElement> obs = null;
        if ("valid".equals(s)) {
            JsonElement from = query.get("from");
            obs = jsonLever.isArray(from) ? queryAsync(from.getAsJsonArray(), query)
                    : queryAsync(from.getAsJsonObject(), query);
        } else {/*from w w w .jav  a  2 s . co m*/
            Exceptions.propagate(new Throwable(s));
        }
        return obs;
    });
}

From source file:com.balajeetm.mystique.util.gson.lever.JsonQuery.java

License:Open Source License

/**
 * Filter./* www . j  av a  2  s  .c  o  m*/
 *
 * @param json the json
 * @param whereElement the where element
 * @return the boolean
 */
private Boolean filter(JsonElement json, JsonElement whereElement) {
    Boolean filter = Boolean.TRUE;
    JsonArray where = jsonLever.asJsonArray(whereElement, new JsonArray());
    for (JsonElement condition : where) {
        if (jsonLever.isString(condition)) {
            String operator = StringUtils.lowerCase(jsonLever.asString(condition));
            if (equalsAny(operator, "&", "&&", "and")) {
                if (filter) {
                    continue;
                } else {
                    return filter;
                }
            }
            if (equalsAny(operator, "|", "||", "or")) {
                if (!filter) {
                    continue;
                } else {
                    return filter;
                }
            }
        } else if (jsonLever.isObject(condition)) {
            String type = jsonLever.getString(condition, "type");
            type = null != type && queryTypes.containsKey(type) ? type : "=";
            filter = queryTypes.get(type).apply(json, condition.getAsJsonObject());
        }
    }
    return filter;
}

From source file:com.baomidou.springwind.util.yuntongxin.CCPRestSDK.java

License:Open Source License

private HashMap<String, Object> jsonToMap(String result) {
    HashMap<String, Object> hashMap = new HashMap<String, Object>();
    JsonParser parser = new JsonParser();
    JsonObject asJsonObject = parser.parse(result).getAsJsonObject();
    Set<Entry<String, JsonElement>> entrySet = asJsonObject.entrySet();
    HashMap<String, Object> hashMap2 = new HashMap<String, Object>();

    for (Entry<String, JsonElement> m : entrySet) {
        if ("statusCode".equals(m.getKey()) || "statusMsg".equals(m.getKey()))
            hashMap.put(m.getKey(), m.getValue().getAsString());
        else {/*from www  .j a v  a  2 s .com*/
            if ("SubAccount".equals(m.getKey()) || "totalCount".equals(m.getKey())
                    || "smsTemplateList".equals(m.getKey()) || "token".equals(m.getKey())
                    || "callSid".equals(m.getKey()) || "state".equals(m.getKey())
                    || "downUrl".equals(m.getKey())) {
                if (!"SubAccount".equals(m.getKey()) && !"smsTemplateList".equals(m.getKey()))
                    hashMap2.put(m.getKey(), m.getValue().getAsString());
                else {
                    try {
                        if ((m.getValue().toString().trim().length() <= 2)
                                && !m.getValue().toString().contains("[")) {
                            hashMap2.put(m.getKey(), m.getValue().getAsString());
                            hashMap.put("data", hashMap2);
                            break;
                        }
                        if (m.getValue().toString().contains("[]")) {
                            hashMap2.put(m.getKey(), new JsonArray());
                            hashMap.put("data", hashMap2);
                            continue;
                        }
                        JsonArray asJsonArray = parser.parse(m.getValue().toString()).getAsJsonArray();
                        ArrayList<HashMap<String, Object>> arrayList = new ArrayList<HashMap<String, Object>>();
                        for (JsonElement j : asJsonArray) {
                            Set<Entry<String, JsonElement>> entrySet2 = j.getAsJsonObject().entrySet();
                            HashMap<String, Object> hashMap3 = new HashMap<String, Object>();
                            for (Entry<String, JsonElement> m2 : entrySet2) {
                                hashMap3.put(m2.getKey(), m2.getValue().getAsString());
                            }
                            arrayList.add(hashMap3);
                        }
                        hashMap2.put(m.getKey(), arrayList);
                    } catch (Exception e) {
                        JsonObject asJsonObject2 = parser.parse(m.getValue().toString()).getAsJsonObject();
                        Set<Entry<String, JsonElement>> entrySet2 = asJsonObject2.entrySet();
                        HashMap<String, Object> hashMap3 = new HashMap<String, Object>();
                        for (Entry<String, JsonElement> m2 : entrySet2) {
                            hashMap3.put(m2.getKey(), m2.getValue().getAsString());
                        }
                        hashMap2.put(m.getKey(), hashMap3);
                        hashMap.put("data", hashMap2);
                    }

                }
                hashMap.put("data", hashMap2);
            } else {

                JsonObject asJsonObject2 = parser.parse(m.getValue().toString()).getAsJsonObject();
                Set<Entry<String, JsonElement>> entrySet2 = asJsonObject2.entrySet();
                HashMap<String, Object> hashMap3 = new HashMap<String, Object>();
                for (Entry<String, JsonElement> m2 : entrySet2) {
                    hashMap3.put(m2.getKey(), m2.getValue().getAsString());
                }
                if (hashMap3.size() != 0) {
                    hashMap2.put(m.getKey(), hashMap3);
                } else {
                    hashMap2.put(m.getKey(), m.getValue().getAsString());
                }
                hashMap.put("data", hashMap2);
            }
        }
    }
    return hashMap;
}

From source file:com.berniesanders.fieldthebern.parsing.CanvassDataSerializer.java

License:Apache License

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

    CanvassData typedContent = null;/*  w ww .  ja va2s .c o m*/
    switch (json.getAsJsonObject().get("type").getAsString()) {
    case ApiAddress.TYPE:
        typedContent = context.deserialize(json, ApiAddress.class);
        break;
    case Person.TYPE:
        typedContent = context.deserialize(json, Person.class);
        break;
    case UserData.TYPE:
        typedContent = context.deserialize(json, UserData.class);
        break;
    default:
        throw new JsonParseException("unknown type:" + json.getAsJsonObject().get("type").getAsString());
    }

    return typedContent;
}

From source file:com.berniesanders.fieldthebern.parsing.CollectionDeserializer.java

License:Apache License

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

    ApiItem typedContent = null;//from   w  w  w  . j a  v a  2 s  .  c  o  m
    switch (json.getAsJsonObject().get("type").getAsString()) {
    case "collection":
        typedContent = context.deserialize(json, Collection.class);
        break;
    case "page":
        typedContent = context.deserialize(json, Page.class);
        break;
    default:
        throw new JsonParseException("unknown type:" + json.getAsJsonObject().get("type").getAsString());
    }

    return typedContent;
}

From source file:com.berniesanders.fieldthebern.parsing.PageContentDeserializer.java

License:Apache License

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

    //Gson gson = new Gson(); //use a temp gson so we don't trigger a stack overflow.
    //Content untypedContent = gson.fromJson(json, Content.class);

    Content typedContent = null;/*from  ww  w .ja  v a2  s . com*/
    switch (json.getAsJsonObject().get("type").getAsString()) {
    case "h1":
        typedContent = context.deserialize(json, H1.class);
        break;
    case "h2":
        typedContent = context.deserialize(json, H2.class);
        break;
    case "h3":
        typedContent = context.deserialize(json, H3.class);
        break;
    case "p":
        typedContent = context.deserialize(json, P.class);
        break;
    case "img":
        typedContent = context.deserialize(json, Img.class);
        break;
    case "nav":
        try {
            typedContent = context.deserialize(json, Nav.class);
        } catch (JsonSyntaxException jsonEx) {
            Timber.e(jsonEx, "Error deserializing a JSON object");
            //use an empty nav item, there is an error in the ftb json
            typedContent = new Nav();
        }
        break;
    case "video":
        typedContent = context.deserialize(json, Video.class);
        break;
    case "quote":
        typedContent = context.deserialize(json, Quote.class);
        break;
    case "list":
        typedContent = context.deserialize(json, List.class);
        break;
    case "iframe":
        typedContent = context.deserialize(json, Iframe.class);
        break;
    default:
        throw new JsonParseException("unknown type:" + json.getAsJsonObject().get("type").getAsString());
    }

    return typedContent;
}

From source file:com.betafase.mcmanager.utils.spiget.PluginInfoRequest.java

public SpigetPlugin[] getPlugins() {
    try {// w  w  w  .  j a  v a2s. co m
        JsonArray a = getAsJsonElement().getAsJsonArray();
        ArrayList<SpigetPlugin> list = new ArrayList<>();
        for (JsonElement e : a.getAsJsonArray()) {
            JsonObject o = e.getAsJsonObject();
            int id = o.get("id").getAsInt();
            SpigetPlugin pl = new SpigetPlugin(id);
            list.add(pl);
        }
        return list.toArray(new SpigetPlugin[list.size()]);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return new SpigetPlugin[0];
}

From source file:com.betafase.mcmanager.utils.Updater.java

License:Creative Commons License

public boolean hasUpdate() {
    try {/*from   w w  w  .j ava2 s .c o  m*/
        PluginDescriptionFile f = plugin.getDescription();
        URL obj = new URL("https://api.betafase.com/plugins/" + f.getName() + "/version");
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("User-Agent", "Mozilla/5.0");
        con.setInstanceFollowRedirects(true);

        int responseCode = con.getResponseCode();
        System.out.println("[" + plugin.getName() + "] Checking for updates");
        if (responseCode != 200) {
            System.out.println("[" + plugin.getName() + "] Response Code : " + responseCode);
            return false;
        }
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        inputLine = response.toString();
        if (inputLine == null) {
            throw new IOException("Could not read Data");
        }
        JsonElement element = new JsonParser().parse(inputLine);
        JsonObject object = element.getAsJsonObject();
        newVersion = object.get("version").getAsString();
        currentVersion = f.getVersion();
        if (!newVersion.equalsIgnoreCase(currentVersion)) {
            newTitle = object.get("title").getAsString();
            newDescription_en = object.get("description_en").getAsString();
            System.out.println("[" + plugin.getName() + "] An Update was found: v" + newVersion);
            return true;
        }
        System.out.println("[" + plugin.getName() + "] You are running the lastest version.");
        return false;
    } catch (Exception ex) {
        System.out.println("[" + plugin.getName() + "] Failed to check for updates: " + ex.getMessage());
        ex.printStackTrace();
        return false;
    }
}