2

First of all, sorry for this silly question.

Can anyone help me out with the code about how to read this JSON file from server? I have messed up my java code after watching several tutorials.

[
  {
    "name": "Coleen Sanford",
    "location": {
      "latitude": -60.489023,
      "longitude": -32.311668
    }
  },
  {
    "name": "Bethany Church",
    "location": {
      "latitude": -1.304805,
      "longitude": -80.670287
    }
  },
  {
    "name": "Kristy Ware",
    "location": {
      "latitude": -46.443562,
      "longitude": -46.426997
    }
  },
  {
    "name": "Avery Navarro",
    "location": {
      "latitude": 35.719469,
      "longitude": -172.783006
    }
  },
  {
    "name": "Robyn Cruz",
    "location": null
  },
  {
    "name": "Vinson Hays",
    "location": null
  }
]

This is my code:

/**
 * Async task class to get json by making HTTP call
 */
private class GetContacts extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        HttpHandler sh = new HttpHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url);

        Log.e(TAG, "Response from url: " + jsonStr);

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                JSONArray  contacts = new JSONArray (jsonStr);

                // looping through All Contacts
                for (int i = 0; i < contacts.length(); i++) {
                    JSONObject c = contacts.getJSONObject(i);

                    String name = c.getString("name");

                    // Phone node is JSON Object
                    JSONObject phone = c.getJSONObject("location");
                    String latitude = phone.getString("latitude");
                    String longitude = phone.getString("longitude");

                    // tmp hash map for single contact
                    HashMap<String, String> contact = new HashMap<>();

                    // adding each child node to HashMap key => value
                    contact.put("name", name);
                    contact.put("latitude", latitude);
                    contact.put("longitude", longitude);

                    // adding contact to contact list
                    contactList.add(contact);
                }
            } catch (final JSONException e) {
                Log.e(TAG, "Json parsing error: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Json parsing error: " + e.getMessage(),
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }
        } else {
            Log.e(TAG, "Couldn't get json from server.");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Couldn't get json from server. Check LogCat for possible errors!",
                            Toast.LENGTH_LONG)
                            .show();
                }
            });

        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();
        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(
                MainActivity.this, contactList,
                R.layout.list_item, new String[]{"name", "latitude",
                "longitude"}, new int[]{R.id.name,
                R.id.latitude, R.id.longitude});

        lv.setAdapter(adapter);
    }

}}
1
  • use optString 'cuz some values are null plus jsonStr is jsonarray Commented Jun 3, 2017 at 16:28

3 Answers 3

3

First you can use Gson Which is a google powerd tool for serializing and de-serializing Json

Then add the gson dependency to your code,

    compile 'com.google.code.gson:gson:2.7'

Next thing you want to do is to create some sample model classes to serialize your json data, use this link and paste your json data and create corresponding classes

Then is the java code, (Lets say your base model class name is UserLocation

Userlocation

    public class UserLocation{
        private Location location;

        private String name;

        public Location getLocation ()
        {
            return location;
        }

        public void setLocation (Location location)
        {
            this.location = location;
        }

        public String getName ()
        {
            return name;
        }

        public void setName (String name)
        {
            this.name = name;
        }
  }

Location

    public class Location {
    private double longitude;

    private double latitude;

    public double getLongitude ()
    {
        return longitude;
    }

    public void setLongitude (double longitude)
    {
        this.longitude = longitude;
    }

    public double getLatitude ()
    {
        return latitude;
    }

    public void setLatitude (double latitude)
    {
        this.latitude = latitude;
    }
}

in code

List<UserLocation> userLocationList = Arrays.asList(new Gson().fromJson(yourResponseString, UserLocation[].class));

This is it, everything will be under this userLocationList

Happy coding.. :)

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

5 Comments

check the pojo class again and json response
edited your answer and let me tell in short, latitude and longitude are of double type in json response not of string type
well no offense, but the Gson converter takes string also will prevent from crashing and agree the fact the its double, but as i said am just providing a sample class. it can be converted as wanted by the user, Cheers @quicklearner
yes , gson is better , does not give null pointer exception when the object is null and thats okay , we all are learning, Enjoy Coding
Exactly my thought. Don't waste time doing primitive deserialization. Use Gson or JAXB.
1

Try that in your AsyncTask for download json file. This method returned String with json.

@Override
    protected String doInBackground(String... urls) {
        try {
            URL url = new URL(urls[0]);

        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setRequestProperty("Authorization", "Basic that_my_Basic_Auth");
        urlConnection.connect();

        InputStream inputStream = urlConnection.getInputStream();
        StringBuffer buffer = new StringBuffer();

        reader = new BufferedReader(new InputStreamReader(inputStream));

        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }

        resultJson = buffer.toString();

    } catch (Exception e) {
        e.printStackTrace();
    }
    return resultJson;
}

Then you can get JSONObject like this:

JSONObject json = new JSONObject(new MyAsyncTask().execute(string_url).get());

Comments

0

Try this You should get contact array correctly and also Latitude and Longitude which is a double type

 if (jsonStr != null) {
        try {
            JSONObject jsonObj = new JSONObject(jsonStr);
            // Getting JSON Array node
            JSONArray contacts = new JSONArray ();
            contacts=jsonObj.getJSONArray("keyforarray")
            // looping through All Contacts
            for (int i = 0; i < contacts.length(); i++) {
                JSONObject c = contacts.getJSONObject(i);
                String name = c.getString("name");
                // Phone node is JSON Object
                JSONObject phone = c.getJSONObject("location");
                double latitude = phone.getDouble("latitude");
                double longitude = phone.getDouble("longitude");
                // tmp hash map for single contact
                HashMap<String, String> contact = new HashMap<>();
                // adding each child node to HashMap key => value
                contact.put("name", name);
                contact.put("latitude", String.valueOf(latitude));
                contact.put("longitude", String.valueOf(longitude));
                // adding contact to contact list
                contactList.add(contact);
            }
        } catch (final JSONException e) {
            Log.e(TAG, "Json parsing error: " + e.getMessage());
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Json parsing error: " + e.getMessage(),
                            Toast.LENGTH_LONG)
                            .show();
                }
            });

        }
    }

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.