android - 作为响应获取单个对象我如何根据我的要求进行解析
问题描述
我以这种方式从 Api 获得响应响应是:
{"path": "{
66.933707682325,
24.876483014725,
66.943130493164,
24.862141543725,
66.943130493164,
24.862141543725,
66.885708125774,
24.7983557697,
66.652607475339,
24.774319574644,
60.05126953125,
20.842286115167,
54.684448242188,
12.567967727957,
54.569091796875,
12.329269107613,
43.26416015625,
-11.264612212504,
43.0224609375,
-11.512322409888,
41.039428710937,
-15.400871114077,
40.294352465028,
-16.761222134799,
35.988464355469,
-23.844140778719,
35.92529296875,
-24.837660759535,
32.71728515625,
-28.751896559604,
32.055628740927,
-29.476657033177,
31.247484170749,
-30.365802730651,
30.399169921875,
-31.316057884407,
28.9599609375,
-32.739519860082,
27.828564008556,
-33.525165333088,
26.724243164062,
-33.959382290645,
24.966430664062,
-34.444054706406,
19.9951171875,
-34.946246767964,
18.314208984375,
-34.368199449564,
-47.552828467179,
-25.776240273816,
-48.290405273438,
-25.624192441212,
-48.33366394043,
-25.613047870816,
-48.345336914062,
-25.546778150624,
-48.371429443359,
-25.529430487502,
-48.398895263672,
-25.53314805514,
-48.414688110352,
-25.542441470125,
-48.444900512695,
-25.538104632759,
-48.472366333008,
-25.530669689516,
-48.472366333008,
-25.530669689516,
-48.507385253906,
-25.554053711007
}"
}
这是纬度和经度
我想在以这种方式传递参数的谷歌地图上绘制折线
LatLng a = new LatLng(24.876483014725, 66.933707682325);
LatLng a = new LatLng(24.7983557697, 66.885708125774);
LatLng a = new LatLng(24.862141543725, 66.943130493164);
那么,我解析我的回复?
解决方案
在kotlin 中,您可以执行以下操作:
val points: List<LatLng> = JSONObject(data)["path"].toString()
.replace("{", "")
.replace("}", "")
.replace("\n","")
.replace(" ","")
.trim()
.split(",")
.onEach { it.trim() }
.chunked(2)
.map { LatLng(it[0].toDouble(), it[1].toDouble()) }
在Java中:
String[] pts = new JSONObject(data).getString("path")
.replace("\n","")
.replace(" ","")
.replace("{","")
.replace("}","")
.split(",");
ArrayList<LatLng> list = new ArrayList<>();
for(int i=0;i<pts.length;i=i+2){
double lat = Double.parseDouble(pts[i]);
double lng = Double.parseDouble(pts[i+1]);
list.add(new LatLng(lat,lng));
}
推荐阅读
- node.js - 为 NodeJS Web 应用程序动态切换 DB
- c - 为什么 strcmp 或 strncmp 不适用于 c 编程语言?
- go - 当我在发送方关闭时,为什么仍然会恐慌“在关闭的通道上发送”?
- python - 用 Openpyxl 编写的公式中的错误:508
- excel - 循环遍历所有子文件夹
- c++ - 引用类内部的类对象不起作用
- android - deleteDirectory: java.lang.NoSuchMethodError: 没有虚拟方法 toPath
- go - 如何使用 mongo-driver 连接到其他包
- mysql - Laravel - DatabaseTransactions - 超过锁定等待超时
- python - 如何解决 Telethon 相关脚本中的“数据库已锁定”