Example usage for com.google.gson JsonParser JsonParser

List of usage examples for com.google.gson JsonParser JsonParser

Introduction

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

Prototype

@Deprecated
public JsonParser() 

Source Link

Usage

From source file:com.citrix.developer.storefront_api_android_sample.ResourceListing.java

License:Open Source License

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //R.layout.activity_resource_listing
    setContentView(R.layout.activity_resource_listing);
    Bundle bndl = this.getIntent().getExtras();
    String JSONResourceList = bndl.getString("JSONRESOURCE");

    //load up the listview.
    _appResources = new ArrayList<Resource>();

    JsonParser parser = new JsonParser();
    JsonElement o = parser.parse(JSONResourceList);
    JsonObject a = o.getAsJsonObject();//from w  w  w.  j  a va 2 s  .com
    JsonArray _resources = a.get("resources").getAsJsonArray();
    for (JsonElement _resource : _resources) {
        JsonObject _obj = _resource.getAsJsonObject();
        Resource _r = new Resource();
        _r.AppTitle = _obj.get("name").getAsString();
        _r.AppLaunchURL = _obj.get("launchurl").getAsString();
        try {
            _r.AppDesc = _obj.get("description").getAsString();
        } catch (Exception descException) {
            //do nothing
        }
        _r.AppIcon = _obj.get("iconurl").getAsString();
        _appResources.add(_r);
    }

    ResourceAdapter _ra = new ResourceAdapter(this, _appResources);

    ListView _lv = (ListView) findViewById(R.id.resourceList);
    _lv.setAdapter(_ra);
    _lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            //get the launch URL
            String url = _appResources.get(i).AppLaunchURL;
            //call the launch task and pass it the launchURL
            new DownloadLaunchICATask(getApplicationContext(), ResourceListing.this).execute(url);
        }
    });
}

From source file:com.cloopen.rest.sdk.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 (Map.Entry<String, JsonElement> m : entrySet) {
        if ("statusCode".equals(m.getKey()) || "statusMsg".equals(m.getKey()))
            hashMap.put(m.getKey(), m.getValue().getAsString());
        else {/*ww  w  .j a va  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 (Map.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 (Map.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 (Map.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.clothcat.hpoolauto.JsonFileHelper.java

License:Open Source License

/**
 * Pretty print the passed string and return ut as a string
 *///from   ww w. ja  va2s.  c  o m
public static String prettify(String json) {
    return new GsonBuilder().setPrettyPrinting().create().toJson(new JsonParser().parse(json));
}

From source file:com.cloud.gate.util.JsonAccessorTestCase.java

License:Apache License

public void testJsonAccessor() {
    JsonParser parser = new JsonParser();
    JsonElement json = parser//from w  ww  .j ava2  s  . co  m
            .parse("{firstName: 'Kelven', lastName: 'Yang', arrayObj: [{name: 'elem1'}, {name: 'elem2'}]}");
    JsonAccessor jsonAccessor = new JsonAccessor(json);

    Assert.assertTrue("Kelven".equals(jsonAccessor.getAsString("firstName")));
    Assert.assertTrue("Kelven".equals(jsonAccessor.getAsString("this.firstName")));
    Assert.assertTrue("Yang".equals(jsonAccessor.getAsString("lastName")));
    Assert.assertTrue("Yang".equals(jsonAccessor.getAsString("this.lastName")));

    Assert.assertTrue("elem1".equals(jsonAccessor.getAsString("arrayObj[0].name")));
    Assert.assertTrue("elem2".equals(jsonAccessor.getAsString("arrayObj[1].name")));

    Assert.assertTrue("elem1".equals(jsonAccessor.getAsString("this.arrayObj.this[0].name")));
    Assert.assertTrue("elem2".equals(jsonAccessor.getAsString("this.arrayObj.this[1].name")));

    Assert.assertTrue(jsonAccessor.getMatchCount("firstName") == 1);
    Assert.assertTrue(jsonAccessor.getMatchCount("middleName") == -1);
    Assert.assertTrue(jsonAccessor.getMatchCount("arrayObj") == 2);
    Assert.assertTrue(jsonAccessor.getMatchCount("arrayObj[0]") == 1);
}

From source file:com.cloud.gate.util.JsonAccessorTestCase.java

License:Apache License

public void testGson() {
    String response = "{ \"queryasyncjobresultresponse\" : {\"jobid\":5868,\"jobstatus\":1,\"jobprocstatus\":0,\"jobresultcode\":0,\"jobresulttype\":\"object\",\"jobresult\":{\"snapshot\":{\"id\":3161,\"account\":\"admin\",\"domainid\":1,\"domain\":\"ROOT\",\"snapshottype\":\"MANUAL\",\"volumeid\":186928,\"volumename\":\"KY-DATA-VOL\",\"volumetype\":\"DATADISK\",\"created\":\"2011-06-02T05:05:41-0700\",\"name\":\"i-2-246446-VM_KY-DATA-VOL_20110602120541\",\"intervaltype\":\"MANUAL\",\"state\":\"BackedUp\"}}}}";

    JsonParser parser = new JsonParser();
    JsonElement json = parser.parse(response);
    JsonAccessor jsonAccessor = new JsonAccessor(json);

    Gson gson = new Gson();
    CloudStackSnapshot snapshot = gson.fromJson(
            jsonAccessor.eval("queryasyncjobresultresponse.jobresult.snapshot"), CloudStackSnapshot.class);

    Assert.assertTrue("BackedUp".equals(snapshot.getState()));
}

From source file:com.cloud.stack.CloudStackClient.java

License:Apache License

public JsonAccessor execute(CloudStackCommand cmd, String apiKey, String secretKey) throws Exception {
    JsonParser parser = new JsonParser();
    URL url = new URL(_serviceUrl + cmd.signCommand(apiKey, secretKey));

    if (logger.isDebugEnabled())
        logger.debug("Cloud API call + [" + url.toString() + "]");

    URLConnection connect = url.openConnection();

    int statusCode;
    statusCode = ((HttpURLConnection) connect).getResponseCode();
    if (statusCode >= 400) {
        logger.error("Cloud API call + [" + url.toString() + "] failed with status code: " + statusCode);
        String errorMessage = ((HttpURLConnection) connect).getResponseMessage();
        if (errorMessage == null) {
            errorMessage = connect.getHeaderField("X-Description");
        }//  w  w w. j av  a2  s  .c  o  m

        if (errorMessage == null) {
            errorMessage = "CloudStack API call HTTP response error, HTTP status code: " + statusCode;
        }

        throw new IOException(errorMessage);
    }

    InputStream inputStream = connect.getInputStream();
    JsonElement jsonElement = parser.parse(new InputStreamReader(inputStream));
    if (jsonElement == null) {
        logger.error(
                "Cloud API call + [" + url.toString() + "] failed: unable to parse expected JSON response");

        throw new IOException("CloudStack API call error : invalid JSON response");
    }

    if (logger.isDebugEnabled())
        logger.debug("Cloud API call + [" + url.toString() + "] returned: " + jsonElement.toString());
    return new JsonAccessor(jsonElement);
}

From source file:com.cloudant.client.api.Database.java

License:Open Source License

/**
 * Find documents using an index/*  www  . j a v a 2s .  c  o  m*/
 *
 * @param selectorJson JSON object describing criteria used to select documents.
 *                     Is of the form <code>"selector": {&lt;your data here&gt;} </code>
 * @param options      {@link FindByIndexOptions query Index options}
 * @param classOfT     The class of Java objects to be returned
 * @return List of classOfT objects
 * @see <a href="http://docs.cloudant.com/api/cloudant-query.html#cloudant-query-selectors">
 * selector syntax</a>
 */
public <T> List<T> findByIndex(String selectorJson, Class<T> classOfT, FindByIndexOptions options) {
    assertNotEmpty(selectorJson, "selectorJson");
    assertNotEmpty(options, "options");

    URI uri = buildUri(getDBUri()).path("_find").build();
    String body = getFindByIndexBody(selectorJson, options);
    InputStream stream = null;
    try {
        stream = getStream(client.executeRequest(createPost(uri, body, "application/json")));
        Reader reader = new InputStreamReader(stream, "UTF-8");
        JsonArray jsonArray = new JsonParser().parse(reader).getAsJsonObject().getAsJsonArray("docs");
        List<T> list = new ArrayList<T>();
        for (JsonElement jsonElem : jsonArray) {
            JsonElement elem = jsonElem.getAsJsonObject();
            T t = client.getGson().fromJson(elem, classOfT);
            list.add(t);
        }
        return list;
    } catch (UnsupportedEncodingException e) {
        // This should never happen as every implementation of the java platform is required
        // to support UTF-8.
        throw new RuntimeException(e);
    } finally {
        close(stream);
    }
}

From source file:com.cloudant.client.api.DatabaseImpl.java

License:Open Source License

@Override
public <T> List<T> findByIndex(String selectorJson, Class<T> classOfT, FindByIndexOptions options) {
    assertNotEmpty(selectorJson, "selectorJson");
    assertNotEmpty(options, "options");

    URI uri = new DatabaseURIHelper(db.getDBUri()).path("_find").build();
    JsonObject body = getFindByIndexBody(selectorJson, options);
    InputStream stream = null;// www .jav a  2  s .  com
    try {
        stream = client.couchDbClient
                .executeToInputStream(createPost(uri, body.toString(), "application/json"));
        Reader reader = new InputStreamReader(stream, "UTF-8");
        JsonArray jsonArray = new JsonParser().parse(reader).getAsJsonObject().getAsJsonArray("docs");
        List<T> list = new ArrayList<T>();
        for (JsonElement jsonElem : jsonArray) {
            JsonElement elem = jsonElem.getAsJsonObject();
            T t = client.getGson().fromJson(elem, classOfT);
            list.add(t);
        }
        return list;
    } catch (UnsupportedEncodingException e) {
        // This should never happen as every implementation of the java platform is required
        // to support UTF-8.
        throw new RuntimeException(e);
    } finally {
        close(stream);
    }
}

From source file:com.cloudant.client.api.Search.java

License:Open Source License

/**
 * Queries a Search Index and returns ungrouped results. In case the query
 * used grouping, an empty list is returned
 *
 * @param <T>      Object type T// w w w.j  a va 2 s. com
 * @param query    the Lucene query to be passed to the Search index
 * @param classOfT The class of type T
 * @return The result of the search query as a {@code List<T> }
 */
public <T> List<T> query(String query, Class<T> classOfT) {
    InputStream instream = null;
    List<T> result = new ArrayList<T>();
    try {
        Reader reader = new InputStreamReader(instream = queryForStream(query), "UTF-8");
        JsonObject json = new JsonParser().parse(reader).getAsJsonObject();
        if (json.has("rows")) {
            if (!includeDocs) {
                log.warn("includeDocs set to false and attempting to retrieve doc. "
                        + "null object will be returned");
            }
            for (JsonElement e : json.getAsJsonArray("rows")) {
                result.add(JsonToObject(db.getGson(), e, "doc", classOfT));
            }
        } else {
            log.warn("No ungrouped result available. Use queryGroups() if grouping set");
        }
        return result;
    } catch (UnsupportedEncodingException e1) {
        // This should never happen as every implementation of the java platform is required
        // to support UTF-8.
        throw new RuntimeException(e1);
    } finally {
        close(instream);
    }
}

From source file:com.cloudant.client.api.Search.java

License:Open Source License

/**
 * Queries a Search Index and returns grouped results in a map where key
 * of the map is the groupName. In case the query didnt use grouping,
 * an empty map is returned//from  ww  w.  jav a2  s .  c o  m
 *
 * @param <T>      Object type T
 * @param query    the Lucene query to be passed to the Search index
 * @param classOfT The class of type T
 * @return The result of the grouped search query as a ordered {@code Map<String,T> }
 */
public <T> Map<String, List<T>> queryGroups(String query, Class<T> classOfT) {
    InputStream instream = null;
    try {
        Reader reader = new InputStreamReader(instream = queryForStream(query), "UTF-8");
        JsonObject json = new JsonParser().parse(reader).getAsJsonObject();
        Map<String, List<T>> result = new LinkedHashMap<String, List<T>>();
        if (json.has("groups")) {
            for (JsonElement e : json.getAsJsonArray("groups")) {
                String groupName = e.getAsJsonObject().get("by").getAsString();
                List<T> orows = new ArrayList<T>();
                if (!includeDocs) {
                    log.warn("includeDocs set to false and attempting to retrieve doc. "
                            + "null object will be returned");
                }
                for (JsonElement rows : e.getAsJsonObject().getAsJsonArray("rows")) {
                    orows.add(JsonToObject(db.getGson(), rows, "doc", classOfT));
                }
                result.put(groupName, orows);
            } // end for(groups)
        } // end hasgroups
        else {
            log.warn("No grouped results available. Use query() if non grouped query");
        }
        return result;
    } catch (UnsupportedEncodingException e1) {
        // This should never happen as every implementation of the java platform is required
        // to support UTF-8.
        throw new RuntimeException(e1);
    } finally {
        close(instream);
    }
}