0

I'm trying to use Json with android I have a link that returns a Json string

InputStream is = new URL(url).openStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);

but, on making a new JSONObject(jsonText); it crushes.

Here is my URL : http://igorsdomain.byethost3.com/getUser.php?username=SailorBoogy&password=qwerty&event=2222

This is the object returned : {"ID":"23","Username":"SailorBoogy","Password":"qwerty","eventID":"6"}

I tried also to JSONObject(jsonText.replaceAll("\"" , "\\\\\"")); but it didn't work.

What's the problem ? am I using it wrong ?

Json Libraries :

org.json.JSONException; org.json.JSONObject; org.json.JSONStringer;

Igor Gumush
  • 61
  • 2
  • 10

3 Answers3

2

I strongly recommend you to use networking libraries such as Volley,Loopj,Okhttp for network operations.

Here is code for your problem.

class LongOpreation extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {

        String str = "";

        try {
            str = sendGetRequest();

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return str;
    }

    public String sendGetRequest() throws MalformedURLException {
        StringBuilder response = new StringBuilder();
        String requrl = "";
        requrl = "http://igorsdomain.byethost3.com/getUser.php?username=SailorBoogy&password=qwerty&event=2222";
        response = requestExecuter(requrl);


        return response.toString();

    }


    @Override
    protected void onPostExecute(String result) {
        try {
            JSONObject jsonObject = new JSONObject(result);
            System.out.println("json-----------------------"+jsonObject);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    @Override
    protected void onPreExecute() {

    }
    public StringBuilder requestExecuter(String str) {
        StringBuilder response = new StringBuilder();
        try {
            URL url = new URL(str);

            HttpURLConnection httpconn = (HttpURLConnection) url
                    .openConnection();
            httpconn.setConnectTimeout(5000);
            httpconn.setReadTimeout(10000);

            if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                BufferedReader input = new BufferedReader(
                        new InputStreamReader(httpconn.getInputStream()));
                String strLine = null;
                while ((strLine = input.readLine()) != null) {
                    response.append(strLine);

                }
                input.close();
            }
            } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return response;
    }
}

Simpley callnew LongOperation().execute(""); and you are done

amodkanthe
  • 4,345
  • 6
  • 36
  • 77
1

First OF all Get your json in network thread like asynchronousTask.

 DefaultHttpClient   httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost(http://someJSONUrl/jsonWebService);
// Depends on your web service
httppost.setHeader("Content-type", "application/json");

InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);           
HttpEntity entity = response.getEntity();

inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();

String line = null;
while ((line = reader.readLine()) != null)
{
    sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) { 
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
} 

And than parse it like this

try {
        JSONObject jObject = new JSONObject(result);
        Log.d("username", jObject.getString("Username"));
        Toast.makeText(getApplicationContext(), jObject.getString("Username"), Toast.LENGTH_LONG).show();
        Log.d("Password", jObject.getString("Password"));
        Log.d("eventID", jObject.getString("eventID"));
    } catch (JSONException e) {
        e.printStackTrace();
    }

For more info checkthis

Community
  • 1
  • 1
Fasiha
  • 488
  • 3
  • 11
0

Without the LogCat it's hard to say, but probably you are doing network operations on MainThread, and Android is complaining with that (because it's a blocking operation, so the UI will freeze) by throwing a android.os.NetworkOnMainThreadException. If this is the case you can solve by doing this operation in another thread (e.g. by using an AsyncTask, or an external library, such as AndroidAsyncHttp)

user2340612
  • 10,053
  • 4
  • 41
  • 66