0

I am having trouble parsing my JSON API -

[
   {
      "Id":1,
      "FirstName":"admin",
      "LastName":"admin",
      "Mobile":null,
      "Email":"rajaish.rolen@gmail.com",
      "UserName":"admin",
      "password":"admin",
      "RoleID":0,
      "CreationDate":"2013-11-15T00:00:00",
      "ModificationDate":"2013-11-15T00:00:00"
   }
]

I've read some tutorials online, with a JSONParser class in which there is a getJSONFromURL method which returns JSONObject. But in all these tutorials their API starts from a JSON Object {, whereas mine starts from an array [. What changes do I need to make so that I can parse this api? Any other way of doing it? Please help me out, its been a head-scratcher for 3 days.

Here is my JSONParser class -

package com.example.projectfortab;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {
    static InputStream is = null;
    static JSONArray jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {
    }

    public JSONArray getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();           

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONArray(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;
    }
}

and here is what I am doing to parse it -

private static final String url = (Some url);                               
private static final String TAG_ID = "CreationDate";
private static final String TAG_FIRSTNAME = "password";
private static final String TAG_LASTNAME = "LastName";
String id;
JSONArray user = null; here


private class JSONParse extends AsyncTask<String, String, JSONArray> {
    private ProgressDialog pDialog;

    @Override
    protected JSONArray doInBackground(String... params) {
    JSONParser jParser = new JSONParser();
     JSONArray json = jParser.getJSONFromUrl(url);
        System.out.println("LENGTH" + json.length());
    try {
        JSONObject json1 = json.getJSONObject(0);
        if(json1.has(TAG_ID))
            id = json1.getString(TAG_ID);
        else
            System.out.println("NO SUCH KEY");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    Log.d("anush", "ID From JSON : " + id);
    return json;
}

when I tried this, logcat showing -

11-19 12:39:44.812: E/JSON Parser(29746): Error parsing data org.json.JSONException: Value {"ExceptionType":"System.NullReferenceException","Message":"An error has occurred.","StackTrace":"   at Lifestyle.Models.UserLoginRepository.Save(UserLogin item) in D:\\project\\LifestyleSolution2\\LifestyleSolution\\LifestyleSolution\\Lifestyle\\Models\\Repository\\UserLoginRepository.cs:line 83\r\n   at Lifestyle.Controllers.UserController.Post(UserLogin user) in D:\\project\\LifestyleSolution2\\LifestyleSolution\\LifestyleSolution\\Lifestyle\\Controllers\\UserController.cs:line 51","ExceptionMessage":"Object reference not set to an instance of an object."} of type org.json.JSONObject cannot be converted to JSONArray

and

11-19 12:39:44.842: E/AndroidRuntime(29746): FATAL EXCEPTION: AsyncTask #1
11-19 12:39:44.842: E/AndroidRuntime(29746): java.lang.RuntimeException: An error occured while executing doInBackground()
11-19 12:39:44.842: E/AndroidRuntime(29746):    at android.os.AsyncTask$3.done(AsyncTask.java:299)
11-19 12:39:44.842: E/AndroidRuntime(29746):    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
11-19 12:39:44.842: E/AndroidRuntime(29746):    at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
11-19 12:39:44.842: E/AndroidRuntime(29746):    at java.util.concurrent.FutureTask.run(FutureTask.java:239)
11-19 12:39:44.842: E/AndroidRuntime(29746):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-19 12:39:44.842: E/AndroidRuntime(29746):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
11-19 12:39:44.842: E/AndroidRuntime(29746):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
11-19 12:39:44.842: E/AndroidRuntime(29746):    at java.lang.Thread.run(Thread.java:856)
11-19 12:39:44.842: E/AndroidRuntime(29746): Caused by: java.lang.NullPointerException
11-19 12:39:44.842: E/AndroidRuntime(29746):    at com.example.projectfortab.FirstActivity$JSONParse.doInBackground(FirstActivity.java:260)
11-19 12:39:44.842: E/AndroidRuntime(29746):    at com.example.projectfortab.FirstActivity$JSONParse.doInBackground(FirstActivity.java:1)
11-19 12:39:44.842: E/AndroidRuntime(29746):    at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-19 12:39:44.842: E/AndroidRuntime(29746):    at java.util.concurrent.FutureTask.run(FutureTask.java:234)
11-19 12:39:44.842: E/AndroidRuntime(29746):    ... 4 more
Jhanvi
  • 5,069
  • 8
  • 32
  • 41
Neeraj Mathur
  • 63
  • 3
  • 8
  • {} is a object notation and [] is a array notation – codeMan Nov 19 '13 at 06:07
  • 1
    In 3 days hope you learn how to get response in `String`. Now you have to create `JSONArray jArray = new JSONArray(response);` – MAC Nov 19 '13 at 06:10
  • well to change your API from array to object, you have to change the way you encode the json results, but since you did show any bit of the api aspect of code not sure how much to advise on. – kabuto178 Nov 19 '13 at 06:10
  • @Neeraj Mathur Check out my answer. – GrIsHu Nov 19 '13 at 06:21

5 Answers5

1

Read the response to a String and then use the following code.

    try {
        JSONObject jsonObject = new JSONArray("ResponseString").getJSONObject(0);
        jsonObject.getString("RequiredStrings");
                    ----
                    ---- 
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
Suneel Prakash
  • 389
  • 5
  • 7
1

try to this..

  String request = value[0];
  response = webAPIRequest.performPost_String(request,null);
  if(response != null)
    {
                Log.i("Message Send Respopnce:==",response);
                try {
                    JSONObject j_object_main=new JSONObject(response);
                    JSONObject j_object_data=j_object_main.optJSONObject("data");

                    success=j_object_data.optString("Success");

                    if(success.equalsIgnoreCase("1"))
                    {

                        JSONArray jarray_news=j_object_data.optJSONArray("newInfo");

            for(int i=0;i<jarray_news.length();i++)
            {
     }
GrIsHu
  • 29,068
  • 10
  • 64
  • 102
Shani Goriwal
  • 2,111
  • 1
  • 18
  • 30
1
 try {
        JSONArray jarray = new JSONArray(Resoponsedata);
       JSONObject jobject = jarray.getJSONObject(0);
        String id =  jobject .getString("Id");
                ---------------
    } catch (JSONException e) {
        e.printStackTrace();
    }

refer http://jsontree.com/

SHASHIDHAR MANCHUKONDA
  • 3,302
  • 2
  • 19
  • 40
0

Try out as below:

JSONArray m_arry = new JSONArray("your response");
    for (int i = 0; i < m_arry.length(); i++) 
      {
    JSONObject m_mydetail = m_arry.getJSONObject(i);

            String id=m_mydetail.getString("Id");
            String firstName=m_mydetail.getString("FirstName");
            String lastName=  m_mydetail.getString("LastName"); 
            String email =m_mydetail.getString("Email");
           ...............................
            //and so on.
     }

For more check HERE

Community
  • 1
  • 1
GrIsHu
  • 29,068
  • 10
  • 64
  • 102
  • I tried the same but logcat showing - 11-19 12:07:36.263: E/JSON Parser(22473): Error parsing data org.json.JSONException: Valueof type org.json.JSONObject cannot be converted to JSONArray – Neeraj Mathur Nov 19 '13 at 06:39
  • @NeerajMathur Can post your logcat error in your question also? – GrIsHu Nov 19 '13 at 06:58
0

Try this:

        URL url1 = new URL("YOUR_URL");
        HttpURLConnection request1 = (HttpURLConnection) url1.openConnection();
        request1.setRequestMethod("GET");
        request1.connect();
        String responseBody = convertStreamToString(request1.getInputStream());
        JSONArray jsonArray = new JSONArray(responseBody);
        for (int i = 0; i < jsonArray.length(); i++) {
            String email = jsonArray.getJSONObject(i).getString("Email");
            System.out.println(email);

            //... Similarly you can parse all the objects..
        }

Method used in above class:

private static String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
        } catch (IOException e) {
        } finally {
            try {
                is.close();
            } catch (IOException e) {
            }
        }

        return sb.toString();
    }
Jhanvi
  • 5,069
  • 8
  • 32
  • 41
  • It does the job, the data is parsing, but writing the whole api as string in source code is not efficient I guess, suppose if there are 100 more objects, then? Will I be writing 100 objects as string in my code? There's gotta b a better way. – Neeraj Mathur Nov 19 '13 at 07:04
  • @NeerajMathur , you dont have to write it in string , you have to pass the response you get from the url here – Jhanvi Nov 19 '13 at 07:14
  • OK, but one more thing, look at my JSONParser class, there is a string named "json", this is supposed to be the response from api, but this is coming null. So, is there any problem with my JSONParser class? – Neeraj Mathur Nov 19 '13 at 07:25
  • @NeerajMathur whats the url?? – Jhanvi Nov 19 '13 at 07:27