Kumar
Kumar

Reputation: 979

Json Parsing from Url In Android , Not working

I am parsing data from URL , Its Getting below mentioned Error.

Raw Data is Showing Perfectly from Server.Not able to Split the Data Using Json Parsing.

Please help me solve this error

EDIT : 1

Json Response from URL

[
    {
        "ID": 4,
        "Name": "Vinoth",
        "Contact": "1111111111",
        "Msg": "1"
    },
    {
        "ID": 5,
        "Name": "Mani",
        "Contact": "22222222",
        "Msg": "1"
    },
    {
        "ID": 6,
        "Name": "Manoj",
        "Contact": "33333333333",
        "Msg": "1"
    }
]

Error :

org.json.JSONException: Value [{"ID":1,"Name":"Lalita","Contact":"9997162499","Msg":"1"},{"ID":2,"Name":"kumar","Contact":"123456789","Msg":"1"}] of type java.lang.String cannot be converted to JSONArray
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at org.json.JSON.typeMismatch(JSON.java:111)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at org.json.JSONArray.<init>(JSONArray.java:96)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at org.json.JSONArray.<init>(JSONArray.java:108)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at com.knowledgeflex.restapidemo.MainActivity$LoadService.onPostExecute(MainActivity.java:135)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at com.knowledgeflex.restapidemo.MainActivity$LoadService.onPostExecute(MainActivity.java:58)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at android.os.AsyncTask.finish(AsyncTask.java:632)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at android.os.AsyncTask.access$600(AsyncTask.java:177)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at android.os.Looper.loop(Looper.java:136)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5584)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at java.lang.reflect.Method.invokeNative(Native Method)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at java.lang.reflect.Method.invoke(Method.java:515)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
12-11 18:23:27.259 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
12-11 18:23:27.259 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at dalvik.system.NativeStart.main(Native Method)

MainActivity.java

public class MainActivity extends Activity {

    TextView name1,email,status,face;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final Button GetServerData = (Button) findViewById(R.id.button1);


      name1 = (TextView)findViewById(R.id.sname);
       email = (TextView)findViewById(R.id.email);
         status = (TextView)findViewById(R.id.status);
       face = (TextView)findViewById(R.id.fb);

        GetServerData.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {

                // Server Request URL
                String serverURL = "http://webapp/api/values";

                // Create Object and call AsyncTask execute Method
                new LoadService().execute(serverURL);

            }
        });

    }


    // Class with extends AsyncTask class
    private class LoadService extends AsyncTask<String, Void, Void> {

        private final HttpClient Client = new DefaultHttpClient();
        private String Content;
        private String Error = null;
        private final String TAG = null;
        String name = null;
        private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);

        TextView uiUpdate = (TextView) findViewById(R.id.textView2);

        protected void onPreExecute() {
            // NOTE: You can call UI Element here.

            // UI Element
            uiUpdate.setText("");
            Dialog.setMessage("Loading service..");
            Dialog.show();
        }

        // Call after onPreExecute method
        protected Void doInBackground(String... urls) {
            try {

                // NOTE: Don't call UI Element here.

                HttpGet httpget = new HttpGet(urls[0]);
                ResponseHandler<String> responseHandler = new BasicResponseHandler();
                Content = Client.execute(httpget, responseHandler);

            } catch (ClientProtocolException e) {
                Error = e.getMessage();
                cancel(true);
            } catch (IOException e) {
                Error = e.getMessage();
                cancel(true);
            }

            return null;
        }

        protected void onPostExecute(Void unused) {
            // Close progress dialog
            Dialog.dismiss();
            Log.e(TAG, "------------------------------------- Output: " + Content);


            try {
                JSONArray jArr=new JSONArray(Content);
                for(int i=0;i<jArr.length();i++) {
                    JSONObject json=jArr.getJSONObject(i);


                    name1.setText(json.getString("Name"));
                    email.setText(json.getString("ID"));
                    status.setText(json.getString("Contact"));
                    face.setText(json.getString("Msg"));

                }

            } catch (JSONException e) {
                e.printStackTrace();
                Log.i("EXCEPTION   ","");
            }

            uiUpdate.setText("Raw Output : " + Content);
        }



    }


}

Upvotes: 11

Views: 3184

Answers (9)

Ajinkya
Ajinkya

Reputation: 1039

Best way and very fast parsing of JSON is GSON liabrary 

dependacy for android studio compile 'com.google.code.gson:gson:2.3.1' OR you can download jar.

Make DTO names of all strings exactly same json of resonse.


Class ClassDTO{
    String ID;
    String Name;
    String Contact;
    String Msg;

    take gettters & setters

}

Just include this lines in your code.


JSONArray array=new JSONArray(Content);
if (array.length() > 0) {
    Gson gson = new Gson();
    int i = 0;
    while (i < array.length()) {
        list.add(gson.fromJson(array.getJSONObject(i).toString(), ClassDTO.class));
        i++;
    }    
} else {
    Toast.makeText(JobCardActivity.this, "No response from server", Toast.LENGTH_LONG).show();
}

Upvotes: 1

Faheem Ahmad Khan
Faheem Ahmad Khan

Reputation: 17

for json url hit and parsing of the data i have use this way First i have created a class for Async request

    public class AsyncRequestForActivities extends
    AsyncTask<String, Integer, String> {

OnAsyncRequestComplete caller;
Context context;

String method = "POST";
List<NameValuePair> parameters = null;
ProgressDialog pDialog = null;
String Progress_msg;

// Three Constructors
public AsyncRequestForActivities(Context a, String m, String Msg,
        List<NameValuePair> p) {
    caller = (OnAsyncRequestComplete) a;
    context = a;
    method = m;
    parameters = p;
    Progress_msg = Msg;
}

public AsyncRequestForActivities(Context a, String m) {
    caller = (OnAsyncRequestComplete) a;
    context = a;
    method = m;

}

public AsyncRequestForActivities(Context a) {
    caller = (OnAsyncRequestComplete) a;
    context = a;
}

// Interface to be implemented by calling activity
public interface OnAsyncRequestComplete {
    public void asyncResponse(String response);
}

public String doInBackground(String... urls) {
    // get url pointing to entry point of API
    String address = urls[0].toString();
    if (method == "POST") {
        return post(address);
    }

    if (method == "GET") {
        return get(address);
    }

    return null;

}

public void onPreExecute() {

    pDialog = new ProgressDialog(context);
    pDialog.setMessage(Progress_msg); // typically you will
    pDialog.setCancelable(false); // define such
    // strings in a remote file.
    pDialog.show();

}

public void onProgressUpdate(Integer... progress) {
    // you can implement some progressBar and update it in this record
    // setProgressPercent(progress[0]);
}

public void onPostExecute(String response) {

    if (pDialog != null && pDialog.isShowing()) {
        pDialog.dismiss();
    }

    caller.asyncResponse(response);
}

protected void onCancelled(String response) {

    if (pDialog != null && pDialog.isShowing()) {
        pDialog.dismiss();
    }
    caller.asyncResponse(response);
}

@SuppressWarnings("deprecation")
private String get(String address) {
    try {

        if (parameters != null) {

            String query = "";
            String EQ = "=";
            String AMP = "&";
            for (NameValuePair param : parameters) {
                query += param.getName() + EQ
                        + URLEncoder.encode(param.getValue()) + AMP;
            }

            if (query != "") {
                address += "?" + query;
            }
        }

        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(address);
        HttpResponse response = client.execute(get);

        return stringifyResponse(response);

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }

    return null;
}

private String post(String address) {
    try {

        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(address);

        if (parameters != null) {
            post.setEntity(new UrlEncodedFormEntity(parameters));
        }

        HttpResponse response = client.execute(post);
        return stringifyResponse(response);

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }

    return null;
}

private String stringifyResponse(HttpResponse response) {
    BufferedReader in;

    try {
        in = new BufferedReader(new InputStreamReader(response.getEntity()
                .getContent()));

        StringBuffer sb = new StringBuffer("");
        String line = "";
        while ((line = in.readLine()) != null) {
            sb.append(line);
        }
        in.close();

        return sb.toString();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

}

now when you want to get Data you have to implement the interface in your activity

    public class SomeClass extends Activity implements OnAsyncRequestComplete{
    // your activity code here

   // some where in class in any function you want
    AsyncRequestForActivities req=new AsyncRequestForActivities(SomeClass.this, MethodType, YourMessage,
        Perameters_in_List<NameValuePareType>);


    req.execute(YourURL);

    }//end of that function
    @Override
    public void asyncResponse(String response) {

    try {

        if (!(response == null)) {
              JSONArray jArray = new JSONArray("response");
                        if (jArray.length()>0){
                            for (int i = 0 ; i < jArray.length();i++){
                                JSONObject jSObject = jArray.getJSONObject(i);
                                int ID = _jSObject.getInt("ID");
                                String Name = _jSObject.getString("Name");
                                String Contact = jSObject.getString("Contact");
                                String Msg = jSObject.getString("Msg");
                                System.out.println("Id : " + ID);
                                System.out.println("Name : " + Name);
                                System.out.println("Contact : " + Contact);
                                System.out.println("Msg : " + Msg);
                            }


        }

    } catch (JSONException e) {
        e.printStackTrace();
    }
    }
    }

Upvotes: 0

Hitesh Bhalala
Hitesh Bhalala

Reputation: 2870

As per your response is JSONArray and gson library is better to use while json data parsing so use below class to any type of data like that

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;


public class ApiData {
    @SerializedName("data")
    @Expose
    private JsonArray Data;

    public <T> List<T> getData(Class<T> c) {
        Type type = new ListParams(c);
        return new Gson().fromJson(Data, type);
    }

    private class ListParams implements ParameterizedType {

        private Type type;

        private ListParams(Type type) {
            this.type = type;
        }

        @Override
        public Type[] getActualTypeArguments() {
            return new Type[]{type};
        }

        @Override
        public Type getRawType() {
            return ArrayList.class;
        }

        @Override
        public Type getOwnerType() {
            return null;
        }


        @Override
        public boolean equals(Object o) {
            return super.equals(o);
        }

    }
}

Create model class like :

public class Model{
   String ID;
   String Name;
   String Contact;
   String msg;
}

Now parse your data like:

ApiData apiData = new Gson().fromJson(Content, ApiData.class);
Lis<Model> models = apiData.getData(Model.class); 

Upvotes: 10

AndiGeeky
AndiGeeky

Reputation: 11474

As i have added escaping to your json here only for storing it temporary :

Please check below parsing code and it is working for me :

String response = "[\r\n    {\r\n        \"ID\": 4,\r\n        \"Name\": \"Vinoth\",\r\n        \"Contact\": \"1111111111\",\r\n        \"Msg\": \"1\"\r\n    },\r\n    {\r\n        \"ID\": 5,\r\n        \"Name\": \"Mani\",\r\n        \"Contact\": \"22222222\",\r\n        \"Msg\": \"1\"\r\n    },\r\n    {\r\n        \"ID\": 6,\r\n        \"Name\": \"Manoj\",\r\n        \"Contact\": \"33333333333\",\r\n        \"Msg\": \"1\"\r\n    }\r\n]";
        try {
            JSONArray jsonArray = new JSONArray(response); // replace response with your response string
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                Log.e("ID", jsonObject.getInt("ID") + "");
                Log.e("Name", jsonObject.getString("Name"));
                Log.e("Contact", jsonObject.getString("Contact"));
                Log.e("Msg", jsonObject.getString("Msg"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

Logs I have printed :

12-17 15:42:54.459 9064-9064/com.example.testapplication E/ID: 4 12-17 15:42:54.459 9064-9064/com.example.testapplication E/Name: Vinoth 12-17 15:42:54.459 9064-9064/com.example.testapplication E/Contact: 1111111111 12-17 15:42:54.459 9064-9064/com.example.testapplication E/Msg: 1 12-17 15:42:54.459 9064-9064/com.example.testapplication E/ID: 5 12-17 15:42:54.459 9064-9064/com.example.testapplication E/Name: Mani 12-17 15:42:54.459 9064-9064/com.example.testapplication E/Contact: 22222222 12-17 15:42:54.459 9064-9064/com.example.testapplication E/Msg: 1 12-17 15:42:54.459 9064-9064/com.example.testapplication E/ID: 6 12-17 15:42:54.459 9064-9064/com.example.testapplication E/Name: Manoj 12-17 15:42:54.459 9064-9064/com.example.testapplication E/Contact: 33333333333 12-17 15:42:54.459 9064-9064/com.example.testapplication E/Msg: 1

Thanks ..!

Upvotes: 6

Vivek Mishra
Vivek Mishra

Reputation: 5705

Check this linkJSONArray

You should not directly use the response you get after hitting web service.First convert it to string as given in the link and also use getInt() when you are parsing your id

Upvotes: 2

Jared Rummler
Jared Rummler

Reputation: 38121

You are using getString on "ID" when you should be using getInt. I tested the JSON string you provided in your question. The following code works:

String json =
    "[{\"ID\":4,\"Name\":\"Vinoth\",\"Contact\":\"1111111111\",\"Msg\":\"1\"},{\"ID\":5,\"Name\":\"Mani\",\"Contact\":\"22222222\",\"Msg\":\"1\"},{\"ID\":6,\"Name\":\"Manoj\",\"Contact\":\"33333333333\",\"Msg\":\"1\"}]";
try {
  JSONArray jsonArray = new JSONArray(json);
  for (int i = 0, len = jsonArray.length(); i < len; i++) {
    JSONObject jsonObject = jsonArray.getJSONObject(i);
    int id = jsonObject.getInt("ID");
    String name = jsonObject.getString("Name");
    String contact = jsonObject.getString("Contact");
    String msg = jsonObject.getString("Msg");
    System.out.println("id=" + id + ", name='" + name + "\', contact='" + contact + "\', msg='" + msg);
  }
} catch (JSONException e) {
  e.printStackTrace();
}

Output from running the above code:

id=4, name='Vinoth', contact='1111111111', msg='1

id=5, name='Mani', contact='22222222', msg='1

id=6, name='Manoj', contact='33333333333', msg='1

If you are still getting an error, post the stacktrace.

Upvotes: 2

learner
learner

Reputation: 3110

 try {
                Object jsonObject = new JSONTokener(Content).nextValue();
                JSONArray jArr=new JSONArray(jsonObject );
                for(int i=0;i<jArr.length();i++) {
                    JSONObject json=jArr.getJSONObject(i);
                    name1.setText(json.getString("Name"));
                    email.setText(json.getString("ID"));
                    status.setText(json.getString("Contact"));
                    face.setText(json.getString("Msg"));

                }

            } catch (JSONException e) {
                e.printStackTrace();
                Log.i("EXCEPTION   ","");
            }

Directly you cannot apply string to array, you should convert string to jsonobject ,then you can do object to array. Hope you understand

Upvotes: 6

cherry-wave
cherry-wave

Reputation: 731

The documentation of public JSONArray (String json) says it throws a

JSONException if the parse fails or doesn't yield a JSONArray.

Maybe he can't handle your response which is quite funny because a simple online json parser can: http://json.parser.online.fr/

As the user "Jelle van Es" mentioned in a previous comment, I would try Gson to do the work. (I would have commented under his comment but I have to few reputation xD)

Upvotes: 2

Shoeb Siddique
Shoeb Siddique

Reputation: 2825

You can Parse your JSON like below.

                    try {
                            JSONArray _jArray = new JSONArray("YOUR_RESPONSE");
                            if (_jArray.length()>0){
                                for (int i = 0 ; i < _jArray.length();i++){
                                    JSONObject _jSObject = _jArray.getJSONObject(i);
                                    int ID = _jSObject.getInt("ID");
                                    String Name = _jSObject.getString("Name");
                                    String Contact = _jSObject.getString("Contact");
                                    String Msg = _jSObject.getString("Msg");
                                    System.out.println("Id : " + ID);
                                    System.out.println("Name : " + Name);
                                    System.out.println("Contact : " + Contact);
                                    System.out.println("Msg : " + Msg);
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

Upvotes: 1

Related Questions