0

I have been struggling with this for hours, what am I doing wrong.

I am trying to parse data from this API using org.json library.

    JSONParser jsonParser = new JSONParser();
    JSONObject obj = (JSONObject) jsonParser.parse(getAllCustomers());


    JSONArray arr = obj.getJSONArray("data");
    for (int i = 0; i < arr.length(); i++) {
        String name = arr.getJSONObject(i).getString("name");     
    }

I dont even know if my code is correct, but I get an error saying that .getJSONArray() cannot find symbol, same with .getJSONObject.

What am I doing wrong here.

JSON:

"data": [
    {
        "id": 1, 
        "name": "Bitcoin", 
        "symbol": "BTC", 
        "website_slug": "bitcoin"
    }, 
    {
        "id": 2, 
        "name": "Litecoin", 
        "symbol": "LTC", 
        "website_slug": "litecoin"
    }, 
    {
        "id": 3, 
        "name": "Namecoin", 
        "symbol": "NMC", 
        "website_slug": "namecoin"
    }, 
    {
        "id": 4, 
        "name": "Terracoin", 
        "symbol": "TRC", 
        "website_slug": "terracoin"
    }, 
    {
        "id": 5, 
        "name": "Peercoin", 
        "symbol": "PPC", 
        "website_slug": "peercoin"
    }, 
    {
        "id": 6, 
        "name": "Novacoin", 
        "symbol": "NVC", 
        "website_slug": "novacoin"
    }, 
    {
        "id": 8, 
        "name": "Feathercoin", 
        "symbol": "FTC", 
        "website_slug": "feathercoin"
    }, 
    {
        "id": 9, 
        "name": "Mincoin", 
        "symbol": "MNC", 
        "website_slug": "mincoin"
    }, 

}

EDIT changed from "posts" to "data". Still issues with the above methods

3
  • can you paste your json? Commented Jun 12, 2018 at 11:53
  • You give us the wrong API. In your API we do not see posts Commented Jun 12, 2018 at 11:53
  • 1
    Please add the entire JSON to the description Commented Jun 12, 2018 at 11:53

2 Answers 2

1

Here you need to do,

JSONArray arr = obj.getJSONArray("data");

instead of

JSONArray arr = obj.getJSONArray("posts");

Since, JsonObject have value key named 'data' not 'posts'

Sign up to request clarification or add additional context in comments.

Comments

1

Check 1: If you are trying to parse the given API, then there is no array with name "posts" at all!! Try with "data" instead :-)

JSONArray arr = obj.getJSONArray("data");

Check 2: You say, you still have the error even after using "data". In that case look at what getAllCustomers() returns. Does it return a valid json string??

Check 3: In case the getAllCustomers() returns a valid JSON, does it contain a "data" element? If yes, is that an Array?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.