Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

Johan Rönkkö
Johan Rönkkö
28,054 Points

Using JSON in android

Let's say i have the following json string from URL. { object: [ { name: "L6q1oxpahQ3" }, { status: "cXnsd61k" } ] }. Here's the link: http://wwwlab.iit.his.se/brom/kurser/mobilprog/jsonservice.php . How do i fetch the data? I tried --> JSONObjekt jsonObj = new JSONObjekt(URL); JSONObject object = jsonObj.getJSONArray(“object”); String name = object.getString(“name”); Am i doing it right? Sorry for wierd code, not sure how to indent etc. in the ask-a-question

1 Answer

aakarshrestha
aakarshrestha
6,509 Points

This is how we can do in JAVA:

compile OkHTTP in your project first.

String url = "http://wwwlab.iit.his.se/brom/kurser/mobilprog/jsonservice.php";

    OkHttpClient client = new OkHttpClient();
    Request request = new Builder()
            .url(url)
            .build();

    Response response = client.newCall(request).execute();

    String json = response.body().string();

    JSONParser parser = new JSONParser();
    Object obj = parser.parse(json);

    JSONObject jsonObject = (JSONObject) obj;
    JSONArray jsonArray = (JSONArray) jsonObject.get("object");

    Iterator iterator = jsonArray.iterator();
    while (iterator.hasNext()) {
        JSONObject jsonObject1 = (JSONObject) iterator.next();
        String name = (String) jsonObject1.get("name");
        System.out.println(name);
    }

It gives you the idea how to do it.

Hope it helps!

Happy coding!