JSON解析错误(Android)
我对Android开发相当陌生,我正试图编写一个程序来解析网站上的一些JSON,并将其输出到ListView中。然而,当我运行我的程序时,我得到了错误:JSON解析错误(Android),android,Android,我对Android开发相当陌生,我正试图编写一个程序来解析网站上的一些JSON,并将其输出到ListView中。然而,当我运行我的程序时,我得到了错误: 05-24 05:37:41.524: E/JSON Parser(783): Error parsing data org.json.JSONException: Value <?xml of type java.lang.String cannot be converted to JSONArray 我知道,空格很糟糕,但这是一个我
05-24 05:37:41.524: E/JSON Parser(783): Error parsing data org.json.JSONException: Value <?xml of type java.lang.String cannot be converted to JSONArray
我知道,空格很糟糕,但这是一个我无法改变的外部来源
我的代码:
从主要活动中:
public class AndroidJSONParsingActivity extends ListActivity {
private static String url = "http://redsox.tcs.auckland.ac.nz/734A/CSService.svc/courses";
private static final String TAG_CODE = "codeField";
private static final String TAG_SEMESTER = "semesterField";
private static final String TAG_TITLE = "titleField";
JSONArray courses = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Hashmap for ListView
ArrayList<HashMap<String, String>> courseList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
courses = jParser.getJSONfromURL(url);
try {
for(int i = 0; i < courses.length(); i++){
JSONObject c = courses.getJSONObject(i);
// Storing each json item in variable
String code = c.getString(TAG_CODE);
String semester = c.getString(TAG_SEMESTER);
String title = c.getString(TAG_TITLE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_CODE, code);
map.put(TAG_SEMESTER, semester);
map.put(TAG_TITLE, title);
// adding HashList to ArrayList
courseList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
//Updating parsed JSON data into ListView
ListAdapter adapter = new SimpleAdapter(this, courseList,
R.layout.list_item,
new String[] { TAG_CODE, TAG_SEMESTER, TAG_TITLE }, new int[] {
R.id.code, R.id.semester, R.id.title });
setListAdapter(adapter);
编辑:完整日志目录为:
05-24 06:48:55.347: D/dalvikvm(787): GC_CONCURRENT freed 68K, 8% free 2736K/2948K, paused 6ms+34ms, total 115ms
05-24 06:48:55.547: E/JSON Parser(787): Error parsing data org.json.JSONException: Value <?xml of type java.lang.String cannot be converted to JSONArray
05-24 06:48:55.547: D/AndroidRuntime(787): Shutting down VM
05-24 06:48:55.547: W/dalvikvm(787): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
05-24 06:48:55.577: E/AndroidRuntime(787): FATAL EXCEPTION: main
05-24 06:48:55.577: E/AndroidRuntime(787): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidhive.jsonparsing/com.androidhive.jsonparsing.AndroidJSONParsingActivity}: java.lang.NullPointerException
05-24 06:48:55.577: E/AndroidRuntime(787): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
05-24 06:48:55.577: E/AndroidRuntime(787): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
05-24 06:48:55.577: E/AndroidRuntime(787): at android.app.ActivityThread.access$600(ActivityThread.java:141)
05-24 06:48:55.577: E/AndroidRuntime(787): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
05-24 06:48:55.577: E/AndroidRuntime(787): at android.os.Handler.dispatchMessage(Handler.java:99)
05-24 06:48:55.577: E/AndroidRuntime(787): at android.os.Looper.loop(Looper.java:137)
05-24 06:48:55.577: E/AndroidRuntime(787): at android.app.ActivityThread.main(ActivityThread.java:5041)
05-24 06:48:55.577: E/AndroidRuntime(787): at java.lang.reflect.Method.invokeNative(Native Method)
05-24 06:48:55.577: E/AndroidRuntime(787): at java.lang.reflect.Method.invoke(Method.java:511)
05-24 06:48:55.577: E/AndroidRuntime(787): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-24 06:48:55.577: E/AndroidRuntime(787): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-24 06:48:55.577: E/AndroidRuntime(787): at dalvik.system.NativeStart.main(Native Method)
05-24 06:48:55.577: E/AndroidRuntime(787): Caused by: java.lang.NullPointerException
05-24 06:48:55.577: E/AndroidRuntime(787): at com.androidhive.jsonparsing.AndroidJSONParsingActivity.onCreate(AndroidJSONParsingActivity.java:44)
05-24 06:48:55.577: E/AndroidRuntime(787): at android.app.Activity.performCreate(Activity.java:5104)
05-24 06:48:55.577: E/AndroidRuntime(787): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
05-24 06:48:55.577: E/AndroidRuntime(787): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
05-24 06:48:55.577: E/AndroidRuntime(787): ... 11 more
05-24 06:48:55.347:D/dalvikvm(787):GC_并发释放68K,8%释放2736K/2948K,暂停6ms+34ms,总计115ms
05-24 06:48:55.547:E/JSON解析器(787):解析数据org.JSON.JSONException时出错:Value您仅在JSON解析器类中创建JSON数组。然后尝试获取一个json对象。
试一试
对于json解析器类,当您(在运行时)获取它时,如下所示:
class LoadAllProducts extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ProductsView.this);
pDialog.setMessage(resStrings.get(0));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected String doInBackground(String... params) {
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(UrlList.url_all_products, "GET", params1);
Log.d(resStrings.get(1), json.toString());
int success = 0;
try {
success = json.getInt(TagList.TAG_SUCCESS);
if (success == 1) {
final JSONArray products = json.getJSONArray(TagList.TAG_PRODUCTS);
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
String id = c.getString(TagList.TAG_PID);
String name = c.getString(TagList.TAG_PNAME);
String quantity = c.getString(TagList.TAG_PQUANTITY);
String price = c.getString(TagList.TAG_PPRICE);
String mod = c.getString(TagList.TAG_PMOD);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TagList.TAG_PID, id);
map.put(TagList.TAG_PNAME, name);
map.put(TagList.TAG_PMOD, mod);
map.put(TagList.TAG_PQUANTITY, quantity);
map.put(TagList.TAG_PPRICE, price);
productsList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
@Override
public void run() {
ListAdapter adapter = new SimpleAdapter(ProductsView.this, productsList, R.layout.list_item, new String[] { TagList.TAG_PID, TagList.TAG_PNAME, TagList.TAG_PMOD, TagList.TAG_PQUANTITY, TagList.TAG_PPRICE }, new int[] { R.id.pid, R.id.pname, R.id.pmod, R.id.pquantity, R.id.pprice });
setListAdapter(adapter);
setProductList();
}
});
}
walls = TileMapFactory.buildMap(tileMap);
for (int i = 0; i < walls.size(); i++) {
mWorldMap[walls.get(i).x][walls.get(i).y].setType(Tile.TYPE_WALL);
}
然后是一个阶级工厂
public class TileMapFactory {
public static ArrayList<Point> buildMap(final String tileMapJson) throws JSONException {
ArrayList<Point> points = new ArrayList<Point>();
final JSONObject jObject = new JSONObject(tileMapJson);
final JSONArray jWalls = jObject.getJSONArray("walls");
for (int i = 0; i < jWalls.length(); i++) {
final JSONArray jWall = jWalls.getJSONArray(i);
points.add(new Point((Integer) jWall.get(0), (Integer) jWall.get(1)));
}
return points;
}
公共类TileMapFactory{
公共静态ArrayList构建映射(最终字符串tileMapJson)抛出JSONException{
ArrayList points=新的ArrayList();
最终JSONObject jObject=新JSONObject(tileMapJson);
final JSONArray jWalls=jObject.getJSONArray(“墙”);
对于(int i=0;i
}
然后您可以像这样访问字符串:
class LoadAllProducts extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ProductsView.this);
pDialog.setMessage(resStrings.get(0));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected String doInBackground(String... params) {
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(UrlList.url_all_products, "GET", params1);
Log.d(resStrings.get(1), json.toString());
int success = 0;
try {
success = json.getInt(TagList.TAG_SUCCESS);
if (success == 1) {
final JSONArray products = json.getJSONArray(TagList.TAG_PRODUCTS);
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
String id = c.getString(TagList.TAG_PID);
String name = c.getString(TagList.TAG_PNAME);
String quantity = c.getString(TagList.TAG_PQUANTITY);
String price = c.getString(TagList.TAG_PPRICE);
String mod = c.getString(TagList.TAG_PMOD);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TagList.TAG_PID, id);
map.put(TagList.TAG_PNAME, name);
map.put(TagList.TAG_PMOD, mod);
map.put(TagList.TAG_PQUANTITY, quantity);
map.put(TagList.TAG_PPRICE, price);
productsList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
@Override
public void run() {
ListAdapter adapter = new SimpleAdapter(ProductsView.this, productsList, R.layout.list_item, new String[] { TagList.TAG_PID, TagList.TAG_PNAME, TagList.TAG_PMOD, TagList.TAG_PQUANTITY, TagList.TAG_PPRICE }, new int[] { R.id.pid, R.id.pname, R.id.pmod, R.id.pquantity, R.id.pprice });
setListAdapter(adapter);
setProductList();
}
});
}
walls = TileMapFactory.buildMap(tileMap);
for (int i = 0; i < walls.size(); i++) {
mWorldMap[walls.get(i).x][walls.get(i).y].setType(Tile.TYPE_WALL);
}
walls=TileMapFactory.buildMap(tileMap);
对于(int i=0;i
在本例中,walls字符串为空,但当您将wall标记替换为CharDebious时,将有一个由2个字符串组成的数组。然后,您可以通过调用例如walls.get(i)来访问类似于arraylist的字符串;在你的例子中,比如codeField。添加新行会弄乱你的json字符串。
尝试更改sb.append(行+“\n”)代码>添加到某人(行)因为“\n”
会弄乱您的字符串。
否则,您的代码看起来很好。我建议您在您的案例中使用AsyncTask
task
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line); // escape will mess up your json string
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
Alhumdulillah.我终于解决了你的问题
您正在对此url发出POST
请求,但这是不允许的。您应该将HTTP请求更改为键入GET
去
并与邮政局核对并获取
在您收到此回复的帖子中:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Service</title>
<style>BODY { color: #000000; background-color: white; font-family: Verdana; margin-left: 0px; margin-top: 0px; } #content { margin-left: 30px; font-size: .70em; padding-bottom: 2em; } A:link { color: #336699; font-weight: bold; text-decoration: underline; } A:visited { color: #6699cc; font-weight: bold; text-decoration: underline; } A:active { color: #336699; font-weight: bold; text-decoration: underline; } .heading1 { background-color: #003366; border-bottom: #336699 6px solid; color: #ffffff; font-family: Tahoma; font-size: 26px; font-weight: normal;margin: 0em 0em 10px -20px; padding-bottom: 8px; padding-left: 30px;padding-top: 16px;} pre { font-size:small; background-color: #e5e5cc; padding: 5px; font-family: Courier New; margin-top: 0px; border: 1px #f0f0e0 solid; white-space: pre-wrap; white-space: -pre-wrap; word-wrap: break-word; } table { border-collapse: collapse; border-spacing: 0px; font-family: Verdana;} table th { border-right: 2px white solid; border-bottom: 2px white solid; font-weight: bold; background-color: #cecf9c;} table td { border-right: 2px white solid; border-bottom: 2px white solid; background-color: #e5e5cc;}</style>
</head>
<body>
<div id="content">
<p class="heading1">Service</p>
<p xmlns="">Method not allowed. Please see the <a rel="help-page" href="http://redsox.tcs.auckland.ac.nz/734A/CSService.svc/help">service help page</a> for constructing valid requests to the service.</p>
</div>
</body>
</html>
服务
正文{color:#000000;背景色:白色;字体系列:Verdana;左边距:0px;右边距:0px;}内容{35;左边距:30px;字体大小:70em;底部填充:2em;}A:链接{color:#336699;字体重量:粗体;文本装饰:下划线;}A:已访问{color:#6699cc;字体重量:粗体;文本装饰:下划线;}A:活动{颜色:#336699;字体大小:粗体;文本装饰:下划线;}。标题1{背景颜色:#003366;边框底部:#336699 6px实心;颜色:#FFFFFFFF;字体系列:Tahoma;字体大小:26px;字体大小:正常;边距:0em 0em 10px-20px;填充底部:8px;填充左侧:30px;填充顶部:16px;}预处理{字体大小:小;背景色:#e5e5cc;填充:5px;字体系列:Courier New;页边距顶端:0px;边框:1px#f0f0e0实心;空白:预换行;空白:-预换行;字换行:中断字;}表格{边框折叠:折叠;边框间距:0px;字体系列:Verdana;}表格th{右边框:2px白色实心;边框底部:2px白色实心;字体大小:粗体;背景色:#cecf9c;}表格td{右边框:2px白色实心;边框底部:2px白色实心;背景色:#e5e5cc;}
服务
方法不允许。请参阅用于构造对服务的有效请求的
这就是为什么你会犯这样的错误
因此,您可以允许从服务器发送POST,也可以在JSONParser
类中做一些更改,将HttpPost
更改为HttpGet
,现在就可以了。谢谢大家。:)我只是在GSON中使用了这些方法,非常简单。感谢大家的帮助
是的,HttpPost也应该是一个HttpGet。你试图获取的url是什么?你上面给出的JSON响应不是完整的,也不是你从web上得到的准确响应。我100%确定它包含在标记中。在这里发布完整的响应。@PareshMayani。虽然我删除了答案,但人们也应该质疑原因e实际上是用来聊天的问题!!@PareshMayani我如何从网络上得到完整准确的回答?你是指我的日志吗?我将编辑我的帖子以包含它。@Nezam我将编辑我的帖子以包含我的代码中使用的URL Frank,看起来你的JSON在第一个节点中有“products”?我的帖子立即以[{“codeField”开头:“COMPSCI 101”…,而不是{courses:[{“codeField”:“COMPSCI 101”…,所以我不确定在这种情况下如何从中获取JSONArray?你应该将我的答案标记为一种解决方案,以公正地对待帖子。
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line); // escape will mess up your json string
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Service</title>
<style>BODY { color: #000000; background-color: white; font-family: Verdana; margin-left: 0px; margin-top: 0px; } #content { margin-left: 30px; font-size: .70em; padding-bottom: 2em; } A:link { color: #336699; font-weight: bold; text-decoration: underline; } A:visited { color: #6699cc; font-weight: bold; text-decoration: underline; } A:active { color: #336699; font-weight: bold; text-decoration: underline; } .heading1 { background-color: #003366; border-bottom: #336699 6px solid; color: #ffffff; font-family: Tahoma; font-size: 26px; font-weight: normal;margin: 0em 0em 10px -20px; padding-bottom: 8px; padding-left: 30px;padding-top: 16px;} pre { font-size:small; background-color: #e5e5cc; padding: 5px; font-family: Courier New; margin-top: 0px; border: 1px #f0f0e0 solid; white-space: pre-wrap; white-space: -pre-wrap; word-wrap: break-word; } table { border-collapse: collapse; border-spacing: 0px; font-family: Verdana;} table th { border-right: 2px white solid; border-bottom: 2px white solid; font-weight: bold; background-color: #cecf9c;} table td { border-right: 2px white solid; border-bottom: 2px white solid; background-color: #e5e5cc;}</style>
</head>
<body>
<div id="content">
<p class="heading1">Service</p>
<p xmlns="">Method not allowed. Please see the <a rel="help-page" href="http://redsox.tcs.auckland.ac.nz/734A/CSService.svc/help">service help page</a> for constructing valid requests to the service.</p>
</div>
</body>
</html>