【问题标题】:JSON formatting a String in androidJSON在android中格式化字符串
【发布时间】:2017-05-22 18:59:03
【问题描述】:

我正在尝试将位置发送到服务器。我应该将这些值发送到服务器。

发送到服务器

{ “type”:”location”,
”id”:”ID”,
”longitude”:”LONGITUDE”,
“latitude”:”LATITUDE” }

我正在尝试发送的字符串

String sendPos = "{\"type\":\"location\",\"id\":\"" +getGrpID() + "\",\"longitude\":\"" + longitude + "\",\"latitude\":\"" + latitude + "}";

我应该返回与我发送的相同的消息,但我没有得到正确的纬度和经度,而是得到了 NaN。

【问题讨论】:

  • NaN 表示不是数字,它可能没有很好的格式,可能是一个字符串并且你没有解析它

标签: java android json server formatting


【解决方案1】:

您不应该手动构建 JSON 字符串。 只需使用框架为您提供的内容来构建 JSON:

JSONObject jObj = new JSONObject();
try {
    jObj.put("type", "location");
    jObj.put("id", getGrpID());
    jObj.put("longitude", longitude);
    jObj.put("latitude", latitude);
} catch (JSONException e) {
    e.printStackTrace();
}

String sendPos = jObj.toString();

【讨论】:

  • 这仍然给我 NaN 作为服务器的结果
  • getGrpID() 返回什么?另外,longitudelatitude 的类型是什么?发送前sendPos的值是多少?
  • getGrpID() 是正确的,经度和纬度我已经硬编码只是为了检查它是否真的注册(它没有)。 sendPos 值为{"type":"location","id":"groupname,heye,1495481010186","longitude":151.211,"latitude":-33.852}
  • 也许服务器需要一个 ID 号?正如你现在所拥有的,它正在为 ID 发送一个字符串。
【解决方案2】:

NaN 是“非数字”的缩写。 NaN 表示监控系统没有接收到任何数值数据。

1 - 坐标真的是合适的格式吗?

2 - 这些值在服务器上是否正确?

坐标必须是“长”类型。

【讨论】:

    【解决方案3】:

    使用 Gson 反序列化。

    第 1 步:创建标准 POJO 类。

    public class Data{
            private String type;
            private String id;
            private double longitude;
            private double latitude;
    
            public Data(String type, String id, double longitude, double latitude) {
                this.type = type;
                this.id = id;
                this.longitude = longitude;
                this.latitude = latitude;
            }
        }
    

    第 2 步:通过 Gson 轻松将其转换为字符串。

    Data data = new Data("location", getGrpID(), longitude, latitude);
    String sendPos = new Gson().toJson(data);
    

    注意:纬度和经度是双精度数据类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-10
      • 2015-09-19
      • 2014-02-13
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多