gpt4 book ai didi

java - 使用 Java 解析 Json 响应

转载 作者:行者123 更新时间:2023-11-29 03:14:52 29 4
gpt4 key购买 nike

我有这个 Restful 网络服务 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):

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

最佳答案

我建议使用像 Apache HttpComponents 这样的库或 UniRest对外部服务器执行 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);

关于java - 使用 Java 解析 Json 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27274474/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com