我这样做很困惑。我要做的是,解析来自服务器的JSONP响应并显示它。是否可以解析Android中的JSONP响应?
以下是我的回复:
{
"Reference1":"String content",
"Reference2":"String content",
"Reference3":"String content",
"Reference4":"String content"
}
谢谢
答案 0 :(得分:0)
填充本身绝不是问题。每个体面的JSON解析库都将以transperantly的方式处理它。我个人非常乐意使用GSON库。我在很多项目中都使用过它,从来没有发现过要抱怨的事情。
PS:也许我误解了你,但是当你说解析时,我假设你需要获取属性的值而不需要保留任何填充,对吗?答案 1 :(得分:0)
我认为这个tutorial非常详细解析android.Hope中的json这对你有帮助。
答案 2 :(得分:0)
我在许多项目中所做的是首先使用以下代码将从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();
}