用Java解析Json响应

时间:2014-12-03 14:41:58

标签: java json rest

我有这个安静的网络服务http://firstsw.besaba.com/get_all.php?tab=doctors&cond=doc_id=2,我用Advanced Rest Client plugin for Chrome对其进行了测试,效果很好。我想用java代码解析Json响应,所以我的代码是:

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

但我得到了这些例外:

Exception in thread "main" org.json.JSONException: JSONObject["success"] not found.
Exception in thread "main" org.json.JSONException: JSONObject["element"] not found.

3 个答案:

答案 0 :(得分:2)

我建议使用像Apache HttpComponentsUniRest这样的库来执行针对外部服务器的http请求(GET,POST等)并返回正确的响应。以下是使用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);

答案 1 :(得分:1)

我认为你的问题是

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

您不能将url用作JSONObject(String)构造函数的参数。

您必须先请求服务器并获取http响应的json字符串

对于获取请求,您应该使用这样的代码

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

发布请求

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

答案 2 :(得分:1)

查看代码时,JSONObject obj = new JSONObject(url)行是有问题的 根据javadoc,url被视为一个对象 这不会产生预期的结果 更好的方法是首先将json内容作为String 替换这部分:

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

请参阅我发现此信息的javadoc: json.org