我正在尝试解析一些JSON并将其发送到我的Android应用程序中的EditText字段。我最近发现我遇到的错误源于我的StringBuilder的内容。我没有使用我的StringBuilder,而是将json样本硬编码为字符串并将其发送到EditText字段。这很好,我得到了我想要出现的价值。但是,我需要通过访问我正在使用的API而不是硬编码来工作。下面是我的JSON Parser类。有没有办法可以在inputStream关闭之前在append之后检查我的stringBuilder中的内容。这样我可以将其排序并将我的jSon返回给stringBuilder.toString()而不是硬编码。
package com.apitest.rottentomatoestest;
import java.io.*;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.*;
import android.util.Log;
public class JSONParser {
static InputStream inputStream = null;
static JSONObject jObject = null;
static String jSon = "";
public JSONParser() {
// TODO Auto-generated constructor stub
}
public JSONObject getJSONFromUrl(String url){
//Make HTTP Request
try {
//defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
inputStream = httpEntity.getContent();
} catch (UnsupportedEncodingException e){
e.printStackTrace();
} catch (ClientProtocolException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null){
stringBuilder.append(line + "\n");
}
inputStream.close();
jSon = "{\"cast\":[{\"id\":\"162661723\",\"name\":\"Snoop Dogg\"}]}";
} catch (Exception e){
Log.e("Buffer Error", "Error converting result " + e.toString());
}
//try to parse the string to JSON Object
try {
jObject = new JSONObject(jSon);
} catch (JSONException e){
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
//return JSON String
return jObject;
}
}
答案 0 :(得分:0)
您可以使用:
Log.d("JSON Contents", stringBuilder.toString());
在你关闭inputStream之前。
更新:596 Service Not Found
消息通常由incorrect URL引起。
答案 1 :(得分:0)
尝试这样做:
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
答案 2 :(得分:0)
您可以使用org.json.JSONObject
将JSON解析为可用的Java对象。