2

I have put a url

private static String url = "http://10.50.101.27:8090/AndroidApp/downloads/result.json";

and tried to parse using json parser in android but it is not working.

My Json format given below:

{"userdetails":[{"address":"Thrissur","name":"Pramoj","userid":"user001"},{"address":"Trivandrum","name":"Santhosh","userid":"user002"}]}

How can I parse. The json parse not responding. Please help me.

1
  • 1
    Show ur parsed code what you tried Commented Nov 26, 2013 at 9:09

8 Answers 8

1

Try this:

JSONObject jObject = new JSONObject(response);
JSONArray jArray = jObject.getJSONArray("userdetails");
for (i = 0; i < jArray.length();i++){
  JSONObject oneObject = jArray.getJSONObject(i);
  oneObject.getString("address");//return the address
  oneObject.getString("name");//return the name
  oneObject.getString("userid");//return the userId
}
Sign up to request clarification or add additional context in comments.

Comments

0
public void parseJson(String jsonString)
{
    try
    {
        JSONObject json = new JSONObject(jsonString);
        JSONArray userdetails = json.getJSONArray("userdetails");
        for (int i=0; i<userdetails.length(); i++)
        {
            JSONObject user = userdetails.getJSONObject(i);
            String address = user.getString("address");
            String name = user.getString("name");
            String userid = user.getString("userid");
        }
    }
    catch (Exception e) {}
}

1 Comment

Problem occured because my IP address is not global!!
0

JSONParser class :

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.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            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 JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

And the parsing code :

JSONParser jParser = new JSONParser();

// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);

try {
    // Getting Array of userdetails
    userdetails = json.getJSONArray("userdetails");

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

        // Storing each json item in variable
        String id = c.getString("userid");
        String name = c.getString("name");
        String address = c.getString(address);
    }
} catch (JSONException e) {
    e.printStackTrace();

Comments

0

First of all convert thr response string from your server to a JSONObject since its structure is a JSONObject. And then get the JSONArray userdetails from that JSONObject. Loop through that array and get the JSONObject's at each individual position. Afterwards get the necessary strings(address,name,userid) fron that JSONObject.

Example code snippet follows..

JSONObject obj = new JSONObject(response);

JSONArray jArr = obj.getJSONArray("userdetails");

for(int i=0; i < jArr.length(); i++)
{
      JSONObject jObj = jArr.getJSONObject(i);

      Log.v("address",jObj.getString("address").trim());

      Log.v("name",jObj.getString("name").trim());

      Log.v("userid",jObj.getString("userid").trim());
}

Comments

0

url="your json url"

    public class Uploadfilechecking extends AsyncTask<String, String, String> {
    Activity mcontext;
    String username, password;
    boolean checkbox_value;

    private ProgressDialog progressDialog;
    private String JSONResp;
    StringBuilder sb = new StringBuilder();
    String Success_msg;

    private JSONArray tmp;

    private View progressView;
    private Object fileUploadManager;
    protected WeakReference<Context> context;

    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub

        try {

            URL u = new URL(url);

            HttpURLConnection conn = (HttpURLConnection) u.openConnection();
            conn.setRequestMethod("GET");

            conn.connect();
            InputStream is = conn.getInputStream();

            // Read the stream
            byte[] b = new byte[1024];
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            while (is.read(b) != -1)
                baos.write(b);

            JSONResp = new String(baos.toByteArray());

        } catch (Throwable t) {
            t.printStackTrace();
        }

        return JSONResp;
    }

    @Override
    protected void onPostExecute(String result) {
        System.out.println("filecheckresult" + result);
        try {

            JSONObject obj = new JSONObject(result);
            JSONArray array=obj.getJSONArray("userdetails");


               for (int i = 0; i < array.length(); i++) {
                   JSONObject actor = array.getJSONObject(i);
                   System.out.println(actor.getString("address"));
            }


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

}

Comments

0
JSONObject jObj = new JSONObject(response);
JSONArray arr = jObj.getJSONArray("userdetails");
for (int i = 0; i < arr .length();i++){
 JSONObject innerobject = arr .getJSONObject(i);
innerobject.getString("address");
innerobject.getString("name");
innerobject.getString("userid");
}

Comments

0

Create class and getter/setter for userdetails

    public class userdetails {
      private String name, address, userid;
    }

Create sink class

      public class Sink {
          List<userdetails> userdetails;
      }

Call that response to sink

   List<userdetails>user_details= new ArrayList<userdetails>();
   SinkItem datas = new Gson().fromJson(response, SinkItem.class);
     user_details= datas.userdetails;

import Gson library to libs folder

Comments

0

JSON Helper Class

public class JSONHelper extends AsyncTask<Void, Void, String> {
    Context context;
    String myUrl;
    ProgressDialog progressDialog;
    OnAsyncLoader onAsyncLoader;
    HashMap<String, String> hashMap;
    JSONObject hashMapWithJson;
    boolean isProgressVisible;


    public JSONHelper(Context context, String url, HashMap<String, String> hashMap, OnAsyncLoader onAsynckLoader, boolean isProgressVisible) {
        this.context = context;
        myUrl = url;
        this.onAsyncLoader = onAsynckLoader;
        this.hashMap = hashMap;
        this.isProgressVisible = isProgressVisible;
    }

    public JSONHelper(Context context, String url, HashMap<String, String> hashMap, OnAsyncLoader onAsynckLoader, boolean isProgressVisible, JSONObject jsonObj) {
        this.context = context;
        myUrl = url;
        this.onAsyncLoader = onAsynckLoader;
        this.hashMap = hashMap;
        this.isProgressVisible = isProgressVisible;
        this.hashMapWithJson = jsonObj;
    }


    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        if (isProgressVisible) {
            progressDialog = new ProgressDialog(context);
            if(Constants.hashMap.containsKey("nop.progressdilog.title"))
                progressDialog.setMessage(Constants.hashMap.get("nop.progressdilog.title"));
            else
                progressDialog.setMessage("Please wait a moment");
            progressDialog.setCancelable(false);
            progressDialog.show();
        }
    }

    @Override
    protected String doInBackground(Void... params) {
        String result = "";
        try {
            URL url = new URL(myUrl);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            if (context!=null) {
                Log.d("JSON_HELPER", url.toString());
            }

            if (hashMap != null) {
                httpURLConnection.setReadTimeout(20000);
                httpURLConnection.setConnectTimeout(20000);
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoInput(true);
                httpURLConnection.setDoOutput(true);

                OutputStream os = httpURLConnection.getOutputStream();
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
                Log.d("LOGDATA", writer.toString());
                writer.write(getPostDataString(hashMap));

                writer.flush();
                writer.close();
                os.close();
            }
            if (hashMapWithJson != null) {
                httpURLConnection.setReadTimeout(20000);
                httpURLConnection.setConnectTimeout(20000);
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoInput(true);
                httpURLConnection.setRequestProperty("Content-Type", "application/json");
                httpURLConnection.setRequestProperty("Accept", "application/json");

                DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
                wr.writeBytes(hashMapWithJson.toString());

        /*OutputStream os = httpURLConnection.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        writer.write(hashMapWithJson.toString());*/
//        writer.write(getPostDataString(hashMap));

                wr.flush();
                wr.close();
//        os.close();
            }
            if (httpURLConnection.getResponseCode() == 200) {
                InputStreamReader inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream());
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String line;

                while ((line = bufferedReader.readLine()) != null) {
                    result += line;
                }
            }
            httpURLConnection.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;

    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        if (isProgressVisible) {
            progressDialog.dismiss();
        }
        try {
            onAsyncLoader.OnResult(s);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }
        return result.toString();
    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.