Vivian Vivian - 3 months ago 7
JSON Question

JSON parsing in android different format

I have php file that has json format output that looks exactly like below:

{"id":"45","name":"testtest","phone":"123456","address":"test123"}


What I want to do is to parse it in my android application and get all the fields of json. The thing is that this format is JSON Object and not JSON Array which makes it hard for me to understand how am I going to parse it. Can you help me figure out how?
Here is where I call the my url and I also have a JSONParser class. The problem is that I get Null Pointer Exception when I am trying to get my object json.getJSONObject(0);

protected String doInBackground(final String... args) {

JSONParser jParser = new JSONParser();
// get JSON data from URL
JSONArray json = jParser.getJSONFromUrl(url);
try {

JSONObject c = json.getJSONObject(0);
String id= c.getString(ID);
String name = c.getString(NAME);
String phone= c.getString(PHONE);
String address= c.getString(ADDRESS);


} catch (JSONException e) {
e.printStackTrace(); }
response = name;

return response;
}

Answer

Its simple ... create JSONObejct from String as you create JSONArray like ;;

JSONObject jsonObject = new JSONObject(provided_json);

Then get a item from jsonObject as

String id= jsonObject .getString(ID);

Full example here ...

//String provided_json = {"id":"45","name":"testtest","phone":"123456","address":"test123"}

    JSONObject jsonObject = new JSONObject(provided_json);
    String id= jsonObject .getString(ID);
    String name = jsonObject .getString(NAME);
    String phone= jsonObject .getString(PHONE);
    String address= jsonObject .getString(ADDRESS);