在 android 中从 JsonObject 中提取坐标
Extracting coordinates from JsonObject in android
我得到 Json 具有不同对象的数组并将它们提取到变量中。
但其中一个对我来说有点困难:
- "query": "Lat -34.88 and Lon 174.76"
我希望能够从这个对象中提取纬度和经度。
我知道如何提取具有开始值和结束值的字符串,但我遇到的问题是坐标长度会发生变化,具体取决于接收到的数据。
基本上我只需要提取纬度,从 "Lat" 加上 space 开始,到 "and" 减去 space 结束。然后再次获取经度,从 "Lon" 开始加上 space...
有人能帮忙吗?
谢谢
试试正则表达式:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("Lat ([-0-9.]*) and Lon ([-0-9.]*)");
checkMatch(pattern, "Lat 34.8.2 and Lon -174.2");
checkMatch(pattern, "Lat -34.4 and Lon 174");
}
private static void checkMatch(Pattern pattern, String latAndLong) {
Matcher matcher = pattern.matcher(latAndLong);
System.out.println(matcher.matches());
System.out.println(matcher.group(0));
System.out.println(matcher.group(1));
System.out.println(matcher.group(2));
}
}
输出
true
Lat 34.8.2 and Lon -174.2
34.8.2
-174.2
true
Lat -34.4 and Lon 174
-34.4
174
您可以使用 String.split(regex) 拆分查询字符串。
String query = "Lat -34.88 and Lon 174.76";
String[] split = query.split(" ");
double lat = Double.parseDouble(split[1]);
double lon = Double.parseDouble(split[4]);
System.out.printf("Lat: %s. Lon: %s", lat, lon);
输出:
Lat: -34.88. Lon: 174.76
我得到 Json 具有不同对象的数组并将它们提取到变量中。 但其中一个对我来说有点困难: - "query": "Lat -34.88 and Lon 174.76"
我希望能够从这个对象中提取纬度和经度。 我知道如何提取具有开始值和结束值的字符串,但我遇到的问题是坐标长度会发生变化,具体取决于接收到的数据。
基本上我只需要提取纬度,从 "Lat" 加上 space 开始,到 "and" 减去 space 结束。然后再次获取经度,从 "Lon" 开始加上 space...
有人能帮忙吗?
谢谢
试试正则表达式:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("Lat ([-0-9.]*) and Lon ([-0-9.]*)");
checkMatch(pattern, "Lat 34.8.2 and Lon -174.2");
checkMatch(pattern, "Lat -34.4 and Lon 174");
}
private static void checkMatch(Pattern pattern, String latAndLong) {
Matcher matcher = pattern.matcher(latAndLong);
System.out.println(matcher.matches());
System.out.println(matcher.group(0));
System.out.println(matcher.group(1));
System.out.println(matcher.group(2));
}
}
输出
true
Lat 34.8.2 and Lon -174.2
34.8.2
-174.2
true
Lat -34.4 and Lon 174
-34.4
174
您可以使用 String.split(regex) 拆分查询字符串。
String query = "Lat -34.88 and Lon 174.76";
String[] split = query.split(" ");
double lat = Double.parseDouble(split[1]);
double lon = Double.parseDouble(split[4]);
System.out.printf("Lat: %s. Lon: %s", lat, lon);
输出:
Lat: -34.88. Lon: 174.76