0

I have a json object being downloaded from my server that returns a result in the following format:

{"Bookname":["Alive-O","All Write Now ","Bun Go Barr 1","Planet Maths","Small World"],"SubjectName":["Religion","English","Irish","Maths","Science"]}

What I want to do is turn that into two different arrays to use on the android device.

Here is the request and the looking for the response within my asynctask

        String[] BookName;
        String[] BookSubject;
        try {
            post.setEntity(new UrlEncodedFormEntity(dataToSend));
            HttpResponse httpResponse = client.execute(post);

            HttpEntity entity = httpResponse.getEntity();
            String result = EntityUtils.toString(entity);
            JSONObject jObject = new JSONObject(result);


        } 

Just wondering how I store the above result in the two arrays?

2 Answers 2

1

It would be something like this

    JSONObject jsonObject = new JSONObject(result);

    // for getting booknames
    JSONArray jsonArray = jsonObject.getJSONArray("Bookname");
    bookName = new String[jsonArray.length()]
    for (int i = 0; i < jsonArray.length(); i++) {
        bookName[i] = jsonArray.getString(i);
    }

    // for getting subjectnames
    jsonArray = jsonObject.getJSONArray("SubjectName");
    bookSubject = new String[jsonArray.length()]
    for (int i = 0; i < jsonArray.length(); i++) {
        bookSubject[i] = jsonArray.getString(i);
    }

Hope it will help..!!

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

1 Comment

Exactly wanted just looking for syntax. Thanks a lot :)
1

Given that you chose JSONObject, that your JSON is that unusual structure, and that you want to mirror that structure in your Java:

Step #1: Call getJSONArray() on jObject() twice, to get the two JSONArray objects (Bookname and SubjectName)

Step #2: Allocate each String[] to be the proper length (call length() on the JSONArray)

Step #3: For each JSONArray, loop over the array indices (0 to length()) and call getString() for each index, assigning it to the appropriate index in the associated String[]

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.