我正在尝试在Android中使用带有JSON的PHP Web服务
我从服务器获得了响应数据
string(170) "["14","Samsung","1","15","Nokia","1","16","Sony Ericson","1","18","LG","1","19","Iphone","1","21","HTC","1","22","Motorola","1","23","Micromax","1","41","BlackBerry","1"]"
我应如何解析它以在ListView上显示它。我熟悉如何通过创建自定义适配器在ListView上显示数据但我无法解析此输出。请帮助
我按照本教程访问PHP Web服务
http://www.codeproject.com/Articles/267023/Send-and-receive-json-between-android-and-php
给我一些参考。
任何帮助表示赞赏
谢谢......
Alos我想知道在php端生成的JSONArray的正确格式是什么?
答案 0 :(得分:4)
首先,它不是一个有效的Json格式,Json必须有label
并且对应value
ex。 “label”:“value”,但您仍然可以手动解析此字符串
像这样
String yourString= "["14","Samsung","1","15","Nokia","1","16","Sony Ericson","1","18","LG","1","19","Iphone","1","21","HTC","1","22","Motorola","1","23","Micromax","1","41","BlackBerry","1"]";
yourString= yourString.subString(1, yourString.length()-1);
String[] arrayValue= yourString.split(",");
现在你有 arrayValue [0] =“14”arrayValue [1] =“三星”等等。
答案 1 :(得分:3)
看起来像'stupid-json'数组。基本上没有问题,因为你将它看作字符串列表。通常我会建议使用一些JSON类,但在这个特殊的简单案例中就足够了:
String jsonString = "["14","Samsung","1","15","Nokia","1","16","Sony Ericson","1","18","LG","1","19","Iphone","1","21","HTC","1","22","Motorola","1","23","Micromax","1","41","BlackBerry","1"]"
jsonString = jsonString.subString(1, substring.length() -1);
String[] singleValues = jsonString.split(",");
这应该导致这个
new String[]{"14","Samsung","1",....}
并且您可以在自定义ListAdapter中传递该String数组(但默认情况下也应该没问题)
答案 2 :(得分:1)
这是有效但奇怪的json响应。 解析这个json时,你将获得27个值。 14,三星,1,15,诺基亚...... 但似乎每3个项目都是一个对象 “14,三星,1” “15,诺基亚,1”。 那个json没有反映出这一点。
使用这样的在线json解析器,您可以看到结果:
http://jsonviewer.stack.hu/
你可以像这样解析json:
List<String> list = new ArrayList<String>();
int counter = 0;
boolean first = true;
String json = "[\"14\",\"Samsung\",\"1\",\"15\",\"Nokia\",\"1\",\"16\",\"Sony Ericson\",\"1\",\"18\",\"LG\",\"1\",\"19\",\"Iphone\",\"1\",\"21\",\"HTC\",\"1\",\"22\",\"Motorola\",\"1\",\"23\",\"Micromax\",\"1\",\"41\",\"BlackBerry\",\"1\"]";
JSONArray getJSONArray;
try {
getJSONArray = new JSONArray(json);
for (int i = 0; i < getJSONArray.length(); i++) {
Log.d("", getJSONArray.getString(i) + "-" + i % 1 + "-" + i % 2);
if ((first == true && counter == 1) || (first == false && counter == 2)) {
list.add(getJSONArray.getString(i));
counter = 0;
first = false;
}
else {
counter += 1;
}
}
}
catch (JSONException e) {
e.printStackTrace();
}
记录您的数组以查看您的内容:
for (String item : list) {
Log.d("list", item);
}
<强>结果:强>
D/list ( 1669): Samsung
D/list ( 1669): Nokia
D/list ( 1669): Sony Ericson
D/list ( 1669): LG
D/list ( 1669): Iphone
D/list ( 1669): HTC
D/list ( 1669): Motorola
D/list ( 1669): Micromax
D/list ( 1669): BlackBerry
对于服务器站点:
通常json必须是这样的..
[
{
id: "14",
brand: "Samsung",
status: "1"
},
{
id: "15",
brand: "Nokia",
status: "1"
},
{
id: "16",
brand: "Sony Ericson",
status: "1"
}
]