【发布时间】:2016-12-22 05:27:15
【问题描述】:
我编写了一个程序来捕获来自服务器的 JSON 响应,其中包含一些我需要的信息。我发现有时我的程序将无法捕获正确的 JSON 字符串,有时它运行良好且没有问题。我尝试检查我的代码以捕获响应,但对此一无所知。当我从服务器检查 JSON 字符串时,它包含我想要的字段,但我的程序无法捕获正确的数据。
这是我的 JSON 字符串
"info":{
"reason":"Fine",
"boolean":false,
"post":{
"actions":"",
"actions_In_process":"Checked",
"destination":"C%3ApdfFdoc%20edipdfFdestinationpdfFexample.pdf",
"file_type":"pdf",
},
这是我捕获 JSON 字符串的程序,我需要的字段是 action_In_process
String Url1 = "http://IP:port/etc/";
HttpURLConnection con = (HttpURLConnection) Url1.openConnection();
con.setRequestMethod("GET");
con.connect();
int responseCode = con.getResponseCode();
if(responseCode == 200)
{
try
{
InputStream is = con.getInputStream();
BufferedReader read = new BufferedReader (new InputStreamReader(is));
StringBuffer buffer = new StringBuffer();
String data = "" ;
while((data = read.readLine() ) != null )
{
buffer.append(data);
}
String JsonData = buffer.toString();
JSONObject jobj = new JSONObject(JsonData);
JSONObject process_info = jobj.getJSONObject("info");
JSONObject pi = process_info.getJSONObject("post");
String action_run = pi.getString("actions_In_process");
System.out.println("Process:" +action_run);
我发现有时进程显示是空白的,但是当我取回 JSON 数据时,我发现我需要的字段在 JSON 响应中。请分享您对这个问题的看法
如果我无法捕获正确的 JSON 字符串,这是显示我的编译器的消息
Process :
如果在正常情况下
Process : check
【问题讨论】:
-
使用 jsonlint.com 验证您的 json 字符串
-
您的“JSON 字符串”不是有效的 JSON。
-
@ScaryWombat - 我已经验证,它包含我想要的数据,但我的程序无法检索它
-
阅读@Henry 的评论
-
您的 json 无效。你的 json 应该像
{ "info": { "reason": "Fine", "boolean": false, "post": { "actions": "", "actions_In_process": "Checked", "destination": "C%3ApdfFdoc%20edipdfFdestinationpdfFexample.pdf", "file_type": "pdf" } } }