0

I want to parse a json array and get its individual elements in android. I have my json file in asset folder. This is type of my json:

{
   "name":"hello",
   "data":[1,2,3,4]
}

I want to get the elements of "data" key such as "1","2","3",& "4" so that I can add it to an array list.The file name is gaitData.json. I tried this method but its not able to read individual elements of array "data". Please help!!

     InputStream is = MainActivity.this.getAssets().open("gaitdata.json");
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        json=new String(buffer,"UTF-8");
        JSONObject object=new JSONObject(json);
        JSONArray hip_min=object.getJSONArray("hip_min");

After this step I iterate the hip_min array using for loop but that does not work either.

2
  • Are you you looking to learn the specifics of JSON or just want to parse it as quick as possible? If the latter I would recommend: github.com/square/moshi Commented Jul 14, 2019 at 20:11
  • Just want to parse it quickly !! Thats it. Commented Jul 15, 2019 at 6:18

1 Answer 1

1

You can get array values like this,

String jsonString = getAssetJsonData("gaitdata.json");
ArrayList<String> list = new ArrayList<>();
try {
    JSONObject jsonObject = new JSONObject(jsonString);
    JSONArray jsonArray = (JSONArray) jsonObject.get("data");
    if (jsonArray != null) {
            for (int i = 0; i < jsonArray.length(); i++) {
                String str = (String) jsonArray.get(i).getValue();
                list.add(str);
            }
    }
} catch (JSONException e) {
       e.printStackTrace();
}

Here is getAssetJsonData() method,

public String getAssetJsonData(String fileName) {
        String json = null;
        try {
            InputStream is = getAssets().open(fileName);
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            json = new String(buffer, "UTF-8");
       } catch (IOException ex) {
            ex.printStackTrace();
            return null;
       }

        Log.e("data", json);
        return json;
    }
Sign up to request clarification or add additional context in comments.

3 Comments

but 'jsonArray = (JSONArray) jsonObject.get("data"); ' will give me the entire array is it? How will I access the elements within it. Shall I use again get method.
also it tell me handle exception for the first code you type and when I do so it does not read the data.
Thanks for the support. Finally now I am able to parse the data using json. Thumbs up for you!!.

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.