我在这样做时感到很困惑。我要做的是,解析来自服务器的 JSONP 响应并显示它。是否可以在 Android 中解析 JSONP 响应?
这是我的回复:
{
"Reference1":"String content",
"Reference2":"String content",
"Reference3":"String content",
"Reference4":"String content"
}
谢谢
我在许多项目中一直在做的是首先使用以下代码将从 http 流读取的字符串转换为 JSONObject:
JSONObject jsonOBJ=new JSONObject(jsonString);
然后使用jsonobject.getString("tag")
读取每个标签。对于您的代码,它将类似于:
String reference1=jsonobject.getString("Reference1");
现在referece1的值=String content
这是我的 http 获取代码:
String url="Your URL Goes Here";
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response;
try {
try
{
InetAddress i = InetAddress.getByName(url);
} catch (UnknownHostException e1) {
e1.printStackTrace();
}
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
stringContent=new StringContent(result);
instream.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
下面是convertStreamToString
块
private static String convertStreamToString(InputStream is)
{
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
填充本身从来都不是问题。每个像样的 JSON 解析库都会透明地处理它。我个人建议您使用GSON库。我在很多项目中都使用过它,从来没有发现什么可抱怨的。
PS:也许我误解了你,但是当你说解析时,我假设你需要获取属性的值并且不需要保留任何填充,对吗?
我认为本教程非常详细地介绍了在 android 中解析 json。希望对您有所帮助。