【发布时间】:2013-05-16 11:06:03
【问题描述】:
我生成一个这样的 json:
["\"纬度\":\"123.0\",\"orden\":\"0\",\"经度\":\"123.0\",\"urlfoto\":\"a \",\"idruta\":\"45\"}","{\"纬度\":\"321.0\",\"orden\":\"1\",\"经度\":\ "321.0\",\"urlfoto\":\"b\",\"idruta\":\"45\"}","{\"纬度\":\"231.0\",\"orden\" :\"2\",\"longitud\":\"231.0\",\"urlfoto\":\"c\",\"idruta\":\"45\"}"]
我在这里搜索并尝试过:
$puntos = $_POST['puntos'];
$data = json_decode($puntos,true);
foreach($data as $obj) {
$idruta = $obj['idruta'];
$orden = $obj['orden'];
$urlfoto = $obj['urlfoto'];
$longitud = $obj['longitud'];
$latitud = $obj['latitud'];
}
非法字符串偏移 'idruta'
foreach($data as $obj) {
$idruta = $obj->idruta;
$orden = $obj->orden;
$urlfoto = $obj->urlfoto;
$longitud = $obj->longitud;
$latitud = $obj->latitud;
}
试图获取非对象的属性
foreach($data as $obj) {
$idruta = $obj[0];
$orden = $obj[1];
$urlfoto = $obj[2];
$longitud = $obj[3];
$latitud = $obj[4];
}
obj[i] 始终为 0 且没有错误。
循环执行 3 次,这样就可以了。
对不起,我只是在学习 JSON 和 php,如果有人可以帮助我获取 JSON 的数据,我将非常高兴。
谢谢!
编辑:感谢您的回答! 我不知道为什么缺少“{”,例如当我在 JSONlint 中粘贴相同的 json 时,它的验证很好,所以......我有点失落抱歉。
这就是我发送 json 的方式:
public void insertPoints(ArrayList<Punto> puntos){
JSONArray array = new JSONArray();
List<NameValuePair> params = new ArrayList<NameValuePair>();
for(Punto p:puntos){
JSONObject obj = new JSONObject();
try {
obj.put("idruta",Integer.toString(p.getIdruta()));
obj.put("orden",Integer.toString(p.getOrden()));
obj.put("urlfoto",p.getUrlfoto());
obj.put("longitud",Double.toString(p.getLongitud()));
obj.put("latitud",Double.toString(p.getLongitud()));
array.put(obj.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpClient httpClient = new DefaultHttpClient();
try {
HttpPost request = new HttpPost(CREATE_POINT);
StringEntity params =new StringEntity("puntos=" + postjson);
request.addHeader("content-type", "application/x-www-form-urlencoded");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
// handle response here...
} catch (Exception ex) {
// handle exception here
} finally {
httpClient.getConnectionManager().shutdown();
}
}
这里有什么问题吗?
谢谢!
【问题讨论】:
-
第一个右括号没有左括号
-
您在第一个
[之后缺少{。 -
不应该有任何`\`。
-
创建 JSON 的东西似乎有问题。看起来它编码了两次,或者是临时完成的并且有错误。修复编码器,我认为你的 PHP 脚本应该可以正常工作。
-
试试这个,你可以自己解决问题;):json.parser.online.fr