android - 将json对象发送到android中的服务器

标签 android json server

我正在尝试使用这种 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对象才能获取depthsize的值(包含在同一个对象中),然后获取location<的JSON对象 获取 xCordyCord 的值:

      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/

相关文章:

Android 将特定 API 调用限制为 3 秒内一次

android - 无法从具有相同身份验证器的不同应用程序添加新的自定义帐户

c# - 如何在c#中获取Json值

django - 如何在 LAN 上设置 Django 服务器

android - 通过使用 Charles 4 拦截网络流量来逆向工程 native 应用程序?

android - 在所有安卓设备上显示图像

android - 当宽度设置为填充父级时,按比例调整 ImageView 的大小

ios - 如何获取json数据并通过segue传递它

javascript - Jquery 的 $.getJSON 的 vanilla JS 版本是什么

angularjs - Firebase 数据库中匹配时发送电子邮件