简体   繁体   中英

Parsing Json response with Java

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.

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);

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM