我正在尝试将从json接收到的字符串格式化为新的格式。实际字符串为[90.36855,23.750088333333334]
,我的目标是将其转换为两个不同的字符串,如90.36855
和23.750088333333334
我尝试了以下方式
String s = "[90.36855,23.750088333333334]";
StringTokenizer st = new StringTokenizer(s, "[");
String lat = st.nextToken();
String lon = st.nextToken();
但它显示FATAL EXCEPTION: main
。我该如何解决这个问题?
答案 0 :(得分:2)
此字符串[
只出现一次。所以在这一行String lon = st.nextToken();
中,它会抛出异常,因为nextToken()
不可用。
由于String
为JSONArray
,您可以使用org.json
获取lat和lon。
E.g:
String s = "[90.36855,23.750088333333334]";
JSONArray jsonArray = new JSONArray(s);
String lat = jsonArray.get(0);
String lon = jsonArray.get(1);
但如果您不想使用JSONArray
,那么StringTokenizer
也可以帮您解决问题。只需使用[],
更新regx:
String s = "[90.36855,23.750088333333334]";
StringTokenizer st = new StringTokenizer(s, "[],");
String lat = st.nextToken();
String lon = st.nextToken();
答案 1 :(得分:0)
使用此代码
String s = "[90.36855,23.750088333333334]";
String result = s.replaceAll("[]","");
StringTokenizer st = new StringTokenizer(result, ",");
String lat = st.nextToken();
String lon = st.nextToken();
答案 2 :(得分:0)
只需用此代码替换您的代码,
String s = "[90.36855,23.750088333333334]";
s = s.substring(1, s.length() - 1); //Trim first and last brackets
StringTokenizer st = new StringTokenizer(s, ","); //pass comma as delimeter
String lat = st.nextToken();
String lon = st.nextToken();
答案 3 :(得分:0)
试试这个。
String s = "[90.36855,23.750088333333334]";
StringTokenizer st = new StringTokenizer(s,",");
String lat = st.nextToken().substring(1);
String lon = st.nextToken();
lon = lon.substring(0,lon.length()-1)