请告诉我如何获得 XML 标记所涵盖的 JSON 响应?
<string>[
{
"value": "America",
"id": "1898"
},
{
"value": "Afghanistan",
"id": "546"
},
{
"value": "China",
"id": "119"
},
{
"value": "Bhutan",
"id": "1884"
}
]<string>
答案 0 :(得分:1)
嗨,请按以下方式找到解决方案,使用下面的代码
String jsonData = null;
XmlPullParserFactory factory;
try {
factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
AssetManager manager = getAssets();
InputStream stream;
stream = manager.open("data.json");
xpp.setInput(new StringReader (getStringFromInputStream(stream)));
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_DOCUMENT) {
System.out.println("Start document");
} else if (eventType == XmlPullParser.END_DOCUMENT) {
System.out.println("End document");
} else if (eventType == XmlPullParser.START_TAG) {
System.out.println("Start tag " + xpp.getName());
} else if (eventType == XmlPullParser.END_TAG) {
System.out.println("End tag " + xpp.getName());
} else if (eventType == XmlPullParser.TEXT) {
System.out.println("Text " + xpp.getText());
jsonData= xpp.getText();
}
eventType = xpp.next();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//parsing json
try {
JSONArray jarray=new JSONArray(jsonData);
for(int i=0;i<jarray.length();i++){
JSONObject jobject=jarray.getJSONObject(i);
String value=jobject.getString("value");
String id=jobject.getString("id");
System.out.println("value " + value);
System.out.println("id " + id);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
getStringFromInputStream方法如下
private static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
为了解决你的问题我只是把你的数据放在带有名称data.jason的资产文件夹中,以后你可以从网络服务中获取这些数据。
<string>[
{
"value": "America",
"id": "1898"
},
{
"value": "Afghanistan",
"id": "546"
},
{
"value": "China",
"id": "119"
},
{
"value": "Bhutan",
"id": "1884"
}
]<string>