我正在尝试使用这种 JSON 格式将 json 发送到 HTTP 服务器:
{"deviceID":3852883413434, "depth":2,"location":{"xCord":46.232, "yCord":42.4421},"size":3}
这是我在 android 中的代码,但似乎运行不正常。也许我需要数组来定位或格式化我的代码。任何建议都可以提供帮助,谢谢。
JSONObject postData = new JSONObject();
try {
postData.put("deviceID", unique_id);
postData.put("depth",((HoleSize)this.getApplication()).getDepth());
postData.put("xCord",((HoleSize)this.getApplication()).getLattitude());
postData.put("yCord",((HoleSize)this.getApplication()).getLongitude());
postData.put("size", ((HoleSize) this.getApplication()).getSize());
new SendData().execute("servername",postData.toString());
} catch (JSONException e) {
e.printStackTrace();
}
最佳答案
使用 json 响应,
{"deviceID":3852883413434, "depth":2,"location":{"xCord":46.232, "yCord":42.4421},"size":3}
必须获取JSON对象才能获取depth
和size
的值(包含在同一个对象中),然后获取location<的JSON对象
获取 xCord
、yCord
的值:
try {
JSONObject postData = new JSONObject(response);
String depth = postData.get("depth").toString();
String size = postData.getInt("size").toString();
JSONObject locationObject = new JSONObject(postData.get("location").toString());
String xCord = locationObject.get("xCord").toString();
String yCord = locationObject.get("yCord").toString();
} catch (JSONException e) {
e.printStackTrace();
}
将此应用于您的代码:
try {
JSONObject postData = new JSONObject(response);
postData.put("deviceID", unique_id);
postData.put("depth",postData.get("depth").toString());
//postData.put("xCord", locationObject.get("xCord").toString());
postData.put("location", postData.get("location").toString());
postData.put("yCord",locationObject.get("yCord").toString());
postData.put("size", postData.getInt("size").toString());
new SendData().execute("servername",postData.toString());
} catch (JSONException e) {
e.printStackTrace();
}
关于android - 将json对象发送到android中的服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49825749/