0

I have a json url link which i would like to read its json response and extract values into variables so that i can use them later

{
  "responseHeader": {
    "status": 0,
    "QTime": 4,
    "params": {
      "q": "*:*",
      "facet.field": "TESTARRAY",
      "indent": "true",
      "rows": "0",
      "wt": "json",
      "facet": "true"
    }
  },
  "response": {
    "numFound": 12,
    "start": 0,
    "docs": []
  },
  "facet_counts": {
    "facet_queries": {},
    "facet_fields": {
      "TESTARRAY": [
        "JON",
        22,
        "SMITH",
        34,
        "ROBERT",
        12
      ]
    },
    "facet_dates": {},
    "facet_ranges": {},
    "facet_intervals": {}
  }
}

For extraction,I am using

JSONObject obj = new JSONObject(IOUtils.toString(new URL(jsonlink), Charset.forName("UTF-8")));
JSONArray arr = obj.getJSONArray("TEST_ARRAY");
        Integer smithage=arr.get("SMITH");

So far this approach is not working. What would be the best way to deal with it Thanks in advance

1
  • small typo problem you have this line JSONArray arr = obj.getJSONArray("TEST_ARRAY"); you dont have a "TEST_ARRAY" but a "TESTARRAY" instead. Other than that JSONObject json = new JSONObject(jsonText); is your answer to converting string resources to json and Integer smithage=arr.get("SMITH"); to hold for future reference Commented Feb 18, 2016 at 22:41

1 Answer 1

0

TEST_ARRAY is not a top-level field, you need to dig down to get it, something like:

JSONObject obj = new JSONObject(IOUtils.toString(new URL(jsonlink), Charset.forName("UTF-8")));
JSONObject facet_counts = obj.getJSONObjecy("facet_counts");
JSONObject facet_fields = facet_counts.getJSONObjecy("facet_fields");
JSONArray test_array = obj.getJSONArray("TESTARRAY");
Integer smithage = test_array.getInt(3);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.