使用 java json 对象转换 将 geometrypointsx11658689660034506y3968183559609521x11658690816565y3968112628238105x11658689660034506y3968183559609521x11658690816565y3968112628238105 转换 为 geometrypoints116586896
可以使用以下代码将json字符串转换为json对象,然后对points数组进行遍历和转换:
import org.json.JSONArray; import org.json.JSONObject;
public class JsonTest {
public static void main(String[] args) {
String jsonStr = "{\"geometry\":{\"points\":[[{\"x\":116.58689660034506,\"y\":39.68183559609521},{\"x\":116.58690816565,\"y\":39.68112628238105}],{\"x\":116.58689660034506,\"y\":39.68183559609521},{\"x\":116.58690816565,\"y\":39.68112628238105}]}}";
JSONObject jsonObject = new JSONObject(jsonStr);
JSONArray pointsArray = jsonObject.getJSONObject("geometry").getJSONArray("points");
JSONArray resultArray = new JSONArray();
for (int i = 0; i < pointsArray.length(); i++) {
JSONArray innerArray = new JSONArray();
Object obj = pointsArray.get(i);
if (obj instanceof JSONArray) {
JSONArray innerPointsArray = (JSONArray) obj;
for (int j = 0; j < innerPointsArray.length(); j++) {
JSONObject pointObj = innerPointsArray.getJSONObject(j);
double x = pointObj.getDouble("x");
double y = pointObj.getDouble("y");
JSONArray pointArray = new JSONArray();
pointArray.put(x);
pointArray.put(y);
innerArray.put(pointArray);
}
} else if (obj instanceof JSONObject) {
JSONObject pointObj = (JSONObject) obj;
double x = pointObj.getDouble("x");
double y = pointObj.getDouble("y");
JSONArray pointArray = new JSONArray();
pointArray.put(x);
pointArray.put(y);
innerArray.put(pointArray);
}
resultArray.put(innerArray);
}
jsonObject.getJSONObject("geometry").put("points", resultArray);
System.out.println(jsonObject.toString());
}
}
运行结果为:
{"geometry":{"points":[[[116.58689660034506,39.68183559609521],[116.58690816565,39.68112628238105]],[[116.58689660034506,39.68183559609521],[116.58690816565,39.68112628238105]]]}
原文地址: https://www.cveoy.top/t/topic/fnRz 著作权归作者所有。请勿转载和采集!