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;

asked Apr 16, 2015 at 16:31
1
  • 1
    Which JSON library are you using? JSON in Java, Jackson, etc? Commented Apr 16, 2015 at 16:33

3 Answers 3

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

answered Apr 16, 2015 at 17:33
Sign up to request clarification or add additional context in comments.

Comments

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

answered Apr 16, 2015 at 17:00

Comments

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)

answered Apr 16, 2015 at 16:37

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.