1

I have this restful web service http://firstsw.besaba.com/get_all.php?tab=doctors&cond=doc_id=2, I tested it with Advanced Rest Client plugin for Chrome and it work well. I want to parse the Json response with java code, so my code is:

import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.*;

public class JsonArray {

    public JsonArray() {
        initJson();
    }
    public void initJson() {
        URL url;
        try {
            url = new URL("http://firstsw.besaba.com/get_all.php?tab=doctors&cond=doc_id=2");     
            JSONObject obj = new JSONObject(url);
            String success = obj.getString("success");
            System.out.println(success+"/n");
            JSONArray arr = obj.getJSONArray("element");
            for(int i=0;i<att.length;i++){
                String doc_id = arr.getJSONObject(i).getString("doc_id");
                String doc_firstname = arr.getJSONObject(i).getString("doc_firstname");
                String doc_lastname = arr.getJSONObject(i).getString("doc_lastname");
                System.out.println("doc_id: "+doc_id+"/n"+"doc_firstname:"+doc_firstname+"/n"+"doc_lastname: "+doc_lastname);
            }
        } catch (MalformedURLException ex) {
            Logger.getLogger(JsonArray.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

But I get those exceptions:

Exception in thread "main" org.json.JSONException: JSONObject["success"] not found.
Exception in thread "main" org.json.JSONException: JSONObject["element"] not found.
8
  • Please provide the JSON response from your service. Commented Dec 3, 2014 at 14:44
  • @LuiggiMendoza use the provided URL: pastebin.com/bRsMA5H2 :) Commented Dec 3, 2014 at 14:46
  • 1
    You couldn't create JSONObject from URL. You should obtain response from service as a first step. Commented Dec 3, 2014 at 14:47
  • Use javadoc: json.org/javadoc/org/json/JSONObject.html . I don't really like those creating constructors with Object as it makes novices think they can pass something like URL there. Commented Dec 3, 2014 at 14:49
  • 1
    @user3417644 Personally I prefer some JAX-RS clients (like Jersey client), but take a look thorugh LuiggiMendoza answer. I think his suggestions are more easier to use. Commented Dec 3, 2014 at 14:59

3 Answers 3

2

I would recommend using a library like Apache HttpComponents or UniRest that executes the http request (GET, POST, etc.) against the external server and returns the proper response. Here's an example using UniRest:

String url = "http://firstsw.besaba.com/get_all.php";
HttpResponse<JsonNode> jsonResponse = Unirest.get(url)
    .queryString("tab", "doctor")
    .queryString("cond", "doc_id=2")
    .asJson();
String jsonContent = jsonResponse.getBody().toString();
//prints the JSON response
System.out.println(jsonContent);
//and you could create your JSON object from here
JSONObject obj = new JSONObject(jsonContent);
Sign up to request clarification or add additional context in comments.

2 Comments

I use your code and I add UniRest.jar in my class path but I get this exception: Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/http/client/methods/HttpGet at com.mashape.unirest.request.BaseRequest.asJson(BaseRequest.java:68)
@user3417644 unirest depends on other libraries. Check here: Don't forget to also install the dependencies (org.json, httpclient 4.3.5, httpmime 4.3.5, httpasyncclient 4.0.2) in the classpath too under Installing/Without Maven section.
1

I think your problem is

            url = new URL("http://firstsw.besaba.com/get_all.php?tab=doctors&cond=doc_id=2");     
        JSONObject obj = new JSONObject(url);

You must not use the url as parameter for the JSONObject(String) constructor.

You have to request the server first and get the json string of the http response

For a get request you should use code like this

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tab", "doctors"));
params.add(new BasicNameValuePair("cond", "doc_id=2"));

HttpParams httpParams = new BasicHttpParams();
HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(httpParams, "UTF-8");
httpParams.setBooleanParameter("http.protocol.expect-continue", false);

final String paramString = URLEncodedUtils.format(params, "UTF-8");
final String urlRequest = "http://firstsw.besaba.com/get_all.php?" + paramString;
final HttpClient httpClient = new DefaultHttpClient(httpParams);
final HttpGet httpGet = new HttpGet(urlRequest);
final HttpResponse httpResponse = httpClient.execute(httpGet);
String jsonString = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
JSONObject jo = new JSONObject(jsonString);

for post request

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tab", "doctors"));
params.add(new BasicNameValuePair("cond", "doc_id=2"));

final HttpParams httpParams = new BasicHttpParams();
HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(httpParams, "UTF-8");
httpParams.setBooleanParameter("http.protocol.expect-continue", false);

final HttpClient httpClient = new DefaultHttpClient(httpParams);
final HttpPost httpPost = new HttpPost("http://firstsw.besaba.com/get_all.php");
httpPost.setEntity(new UrlEncodedFormEntity(params));
final HttpResponse httpResponse = httpClient.execute(httpPost);
String jsonString = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
JSONObject jo = new JSONObject(jsonString);

3 Comments

You forgot to specify that you're using Apache HttpComponents.
@Martin_Ma are you using any extra library?
I copied the code from an old android project of mine. I think the library is part of androids default librarys. You are right, it´s out of apache httpcomponents. You have to add the library to your project
1

Looking at your code the line JSONObject obj = new JSONObject(url) is problematic.
According to the javadoc the url is seen as an Object.
This will not give the desired result.
Better is to get the json content as String first.
Replace this part :

        url = new URL("http://firstsw.besaba.com/get_all.php?tab=doctors&cond=doc_id=2");

        String content = (String)url.getContent();
        JSONObject obj = new JSONObject(content);
        String success = obj.getString("success");
        System.out.println(success+"/n");
        JSONArray arr = obj.getJSONArray("element");

See the javadoc where I found this info: json.org

1 Comment

Exception: java.lang.ClassCastException: sun.net.www.protocol.http.HttpURLConnection$HttpInputStream cannot be cast to java.lang.String

Your Answer

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.