Example usage for com.google.gson JsonElement isJsonObject

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

Introduction

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

Prototype

public boolean isJsonObject() 

Source Link

Document

provides check for verifying if this element is a Json object or not.

Usage

From source file:com.github.zhizheng.json.JsonValueTypes.java

License:Apache License

/**
 *  Json /*from ww  w .  j a va2s .  c o m*/
 * 
 * @param jsonElement
 * @return
 */
public static String getJsonValueType(JsonElement jsonElement) {
    if (jsonElement.isJsonObject()) {
        return OBJECT.toString();
    }
    if (jsonElement.isJsonArray()) {
        return ARRAY.toString();
    }
    if (jsonElement.isJsonPrimitive()) {
        JsonPrimitive asJsonPrimitive = jsonElement.getAsJsonPrimitive();
        if (asJsonPrimitive.isBoolean()) {
            return BOOLEAN.toString();
        }
        if (asJsonPrimitive.isNumber()) {
            return NUMBER.toString();
        }
        return STRING.toString();
    }
    return NULL.toString();
}

From source file:com.gmail.tracebachi.DeltaSkins.Shared.Storage.PlayerProfileStorage.java

License:Open Source License

public int deserialize(JsonArray array) {
    Preconditions.checkNotNull(array, "Array was null.");

    int loaded = 0;

    for (JsonElement element : array) {
        if (element.isJsonObject()) {
            try {
                PlayerProfile profile = PlayerProfile.deserialize(element.getAsJsonObject());

                profileMap.put(profile.getName().toLowerCase(), profile);
                loaded += 1;//  www  .  j a va2  s .  c  o m
            } catch (NullPointerException e) {
                e.printStackTrace();
            }
        }
    }

    return loaded;
}

From source file:com.gmail.tracebachi.DeltaSkins.Shared.Storage.SkinDataStorage.java

License:Open Source License

public int deserialize(JsonArray array) {
    Preconditions.checkNotNull(array, "Array was null.");

    int loaded = 0;

    for (JsonElement element : array) {
        if (element.isJsonObject()) {
            try {
                SkinData skinData = SkinData.deserialize(element.getAsJsonObject());

                skinDataMap.put(skinData.getUuid(), skinData);
                loaded += 1;/*from  w w w  .j  a v a 2  s  .  c om*/
            } catch (NullPointerException e) {
                e.printStackTrace();
            }
        }
    }

    return loaded;
}

From source file:com.google.appinventor.components.runtime.GoogleMap.java

License:Open Source License

@SimpleFunction(description = "Adding a list of markers that are represented as JsonArray. "
        + " The inner JsonObject represents a marker"
        + "and is composed of name-value pairs. Name fields for a marker are: "
        + "\"lat\" (type double) [required], \"lng\"(type double) [required], "
        + "\"color\"(type int)[in hue value ranging from 0~360], "
        + "\"title\"(type String), \"snippet\"(type String), \"draggable\"(type boolean)")
public void AddMarkersFromJson(String jsonString) {
    ArrayList<Integer> markerIds = new ArrayList<Integer>();
    JsonParser parser = new JsonParser();
    float[] hsv = new float[3];

    // parse jsonString into jsonArray
    try {/*from w ww .  j  ava 2s  .  c o  m*/
        JsonElement markerList = parser.parse(jsonString);
        if (markerList.isJsonArray()) {
            JsonArray markerArray = markerList.getAsJsonArray();

            Log.i(TAG, "It's a JsonArry: " + markerArray.toString());
            for (JsonElement marker : markerArray) {
                boolean addOne = true;
                // now we have marker
                if (marker.isJsonObject()) {
                    JsonObject markerJson = marker.getAsJsonObject();
                    if (markerJson.get("lat") == null || markerJson.get("lng") == null) {
                        addOne = false;

                    } else { // having correct syntax of a marker in Json

                        // check for cases: "lat" : "40.7561"  (as String)
                        JsonPrimitive jpLat = (JsonPrimitive) markerJson.get("lat");
                        JsonPrimitive jpLng = (JsonPrimitive) markerJson.get("lng");

                        double latitude = 0;
                        double longitude = 0;

                        try { //it's possible that when converting to Double, we will have errors
                              // for example, some json has "lat": "" (empty string for lat, lng values)

                            if (jpLat.isString() && jpLng.isString()) {
                                Log.i(TAG, "jpLat:" + jpLat.toString());
                                Log.i(TAG, "jpLng:" + jpLng.toString());

                                latitude = new Double(jpLat.getAsString());
                                longitude = new Double(jpLng.getAsString());
                                Log.i(TAG, "convert to double:" + latitude + "," + longitude);
                            } else {
                                latitude = markerJson.get("lat").getAsDouble();
                                longitude = markerJson.get("lng").getAsDouble();
                            }

                        } catch (NumberFormatException e) {
                            addOne = false;
                        }
                        // check for Lat, Lng correct range

                        if ((latitude < -90) || (latitude > 90) || (longitude < -180) || (longitude > 180)) {
                            Log.i(TAG, "Lat/Lng wrong range:" + latitude + "," + longitude);
                            addOne = false;

                        }

                        Color.colorToHSV(mMarkerColor, hsv);
                        float defaultColor = hsv[0];
                        float color = (markerJson.get("color") == null) ? defaultColor
                                : markerJson.get("color").getAsInt();

                        if ((color < 0) || (color > 360)) {
                            Log.i(TAG, "Wrong color");
                            addOne = false;
                        }

                        String title = (markerJson.get("title") == null) ? ""
                                : markerJson.get("title").getAsString();
                        String snippet = (markerJson.get("snippet") == null) ? ""
                                : markerJson.get("snippet").getAsString();
                        boolean draggable = (markerJson.get("draggable") == null) ? mMarkerDraggable
                                : markerJson.get("draggable").getAsBoolean();

                        if (addOne) {
                            Log.i(TAG, "Adding marker" + latitude + "," + longitude);
                            int uniqueId = generateMarkerId();
                            markerIds.add(uniqueId);
                            addMarkerToMap(latitude, longitude, uniqueId, color, title, snippet, draggable);
                        }
                    }
                }
            } //end of JsonArray

        } else { // not a JsonArray
            form.dispatchErrorOccurredEvent(this, "AddMarkersFromJson",
                    ErrorMessages.ERROR_GOOGLE_MAP_INVALID_INPUT,
                    "markers needs to be represented as JsonArray");
            markersList = YailList.makeList(markerIds);
        }

    } catch (JsonSyntaxException e) {
        form.dispatchErrorOccurredEvent(this, "AddMarkersFromJson",
                ErrorMessages.ERROR_GOOGLE_MAP_JSON_FORMAT_DECODE_FAILED, jsonString);
        markersList = YailList.makeList(markerIds); // return an empty markerIds list
    }

    markersList = YailList.makeList(markerIds);
    //  return YailList.makeList(markerIds);
}

From source file:com.google.code.bing.search.client.impl.BingSearchJsonClientImpl.java

License:Apache License

@SuppressWarnings("unchecked")
protected <T> T unmarshallObject(Class<T> clazz, InputStream jsonContent) {
    try {/*w  ww  .  j  av a 2  s .  c  o m*/
        JsonElement response = parser.parse(new InputStreamReader(jsonContent, UTF_8_CHAR_SET));
        if (response.isJsonObject()) {
            if (response.getAsJsonObject().get("SearchResponse") != null) {
                Gson gson = getGsonBuilder().create();
                return (T) gson.fromJson(response.getAsJsonObject().get("SearchResponse"), clazz);
            }
        }
        throw new BingSearchException("Unknown content found in response:" + response.toString());
    } catch (Exception e) {
        throw new BingSearchException(e);
    }
}

From source file:com.google.code.bing.search.client.impl.BingSearchJsonClientImpl.java

License:Apache License

/**
 * Unmarshall./*from  w  w  w .j av a  2 s .c  o  m*/
 * 
 * @param jsonContent the json content
 * 
 * @return the json object
 */
protected JsonObject unmarshall(InputStream jsonContent) {
    try {
        JsonElement element = parser.parse(new InputStreamReader(jsonContent, UTF_8_CHAR_SET));
        if (element.isJsonObject()) {
            return element.getAsJsonObject();
        } else {
            throw new BingSearchException("Unknown content found in response." + element);
        }
    } catch (Exception e) {
        throw new BingSearchException(e);
    } finally {
        closeStream(jsonContent);
    }
}

From source file:com.google.code.stackexchange.client.impl.StackExchangeApiJsonClient.java

License:Apache License

protected <T> PagedList<T> unmarshallList(Class<T> clazz, InputStream jsonContent) {
    try {//from  w  ww  .  ja  va  2  s. c o m
        JsonElement response = parser.parse(new InputStreamReader(jsonContent, UTF_8_CHAR_SET));
        if (response.isJsonObject()) {
            JsonObject adaptee = response.getAsJsonObject();
            PagedList<T> list = new PagedArrayList<T>();
            if (adaptee.has("total")) {
                list.setTotal(adaptee.get("total").getAsLong());
            }
            if (adaptee.has("page")) {
                list.setPage(adaptee.get("page").getAsInt());
            }
            if (adaptee.has("pagesize")) {
                list.setPageSize(adaptee.get("pagesize").getAsInt());
            }
            String placeHolder = LIST_PLACE_HOLDERS.get(clazz);
            if (adaptee.has(placeHolder)) {
                JsonArray elements = adaptee.get(placeHolder).getAsJsonArray();
                if (elements != null) {
                    Gson gson = getGsonBuilder().create();
                    for (JsonElement o : elements) {
                        list.add(gson.fromJson(o, clazz));
                    }
                }
            }
            return list;
        }
        throw new StackExchangeApiException("Unknown content found in response:" + response.toString());
    } catch (Exception e) {
        throw new StackExchangeApiException(e);
    }
}

From source file:com.google.code.stackexchange.client.impl.StackExchangeApiJsonClient.java

License:Apache License

protected <T> T unmarshallObject(Class<T> clazz, InputStream jsonContent) {
    if (clazz.equals(Error.class)) {
        try {//from   w  w w. j av a 2 s .co m
            JsonElement response = parser.parse(new InputStreamReader(jsonContent, UTF_8_CHAR_SET));
            if (response.isJsonObject()) {
                JsonObject adaptee = response.getAsJsonObject();
                Gson gson = getGsonBuilder().create();
                return gson.fromJson(adaptee.get("error"), clazz);
            }
        } catch (Exception e) {
            throw new StackExchangeApiException(e);
        }
    }
    return null;
}

From source file:com.google.code.stackexchange.client.query.impl.BaseStackOverflowApiQuery.java

License:Apache License

@Override
public PagedList<T> list() {
    InputStream jsonContent = null;
    try {//  w  w w  .  j  a v  a2  s . c o m
        jsonContent = callApiMethod(apiUrlBuilder.buildUrl());
        JsonElement response = parser.parse(new InputStreamReader(jsonContent, UTF_8_CHAR_SET));
        if (response.isJsonObject()) {
            PagedList<T> responseList = unmarshall(response.getAsJsonObject());
            notifyObservers(responseList);
            return responseList;
        }
        throw new StackExchangeApiException("Unknown content found in response:" + response.toString());
    } catch (Exception e) {
        throw new StackExchangeApiException(e);
    } finally {
        closeStream(jsonContent);
    }
}

From source file:com.google.code.stackexchange.client.query.impl.BaseStackOverflowApiQuery.java

License:Apache License

@Override
public T singleResult() {
    InputStream jsonContent = null;
    try {//w  w w  . j a  va  2  s .  co m
        jsonContent = callApiMethod(apiUrlBuilder.buildUrl());
        JsonElement response = parser.parse(new InputStreamReader(jsonContent, UTF_8_CHAR_SET));
        if (response.isJsonObject()) {
            PagedList<T> responseList = unmarshall(response.getAsJsonObject());
            notifyObservers(responseList);
            return getFirstElement(responseList);
        }
        throw new StackExchangeApiException("Unknown content found in response:" + response.toString());
    } catch (Exception e) {
        throw new StackExchangeApiException(e);
    } finally {
        closeStream(jsonContent);
    }
}