我尝试从 JSON 数据中获取整数。但是每当调用该方法时,我都会收到错误:
Undeterminated object at character 16 of {"lat": 47175650
这是我的 JSON 数据:[{"lat": 47175650, "lon": 7637853}]
这是我读取数据的代码。它适用于 Android 应用程序,它从文件中获取数据,将 JSON 数组中的所有对象放入字符串数组中,并应创建与对象一样多的 GeoPoint:
public void loadData(){
File f = new File("/data/data/com.example.app/files/file.txt");
if (f.exists()) {
String locations = null;
try {
FileInputStream loadLoc = openFileInput("file.txt");
List<Byte> data = new ArrayList<Byte>();
while (true) {
int b = loadLoc.read();
if (b == -1)
break; // end of file
else
data.add((byte) b);
}
// bytes to string
byte[] bytes = new byte[data.size()];
for (int i = 0; i<bytes.length; i++)
bytes[i] = data.get(i);
locations = new String(bytes);
Log.e("debug", locations);
loadLoc.close();
} catch (Exception ex) {
Log.e("debug", ex.getMessage());
}
locations = locations.substring(1, locations.length()-1);
String[] points = locations.split(",");
JSONObject json;
GeoPoint p;
try {
for (int i=0; i<points.length; i++) {
json = new JSONObject(points[i]);
// I guess the "getInt()"s here are the problem
p = new GeoPoint(json.getInt("lat"), json.getInt("lon"));
overlay.addItem(p, "location", "location");
}
} catch (JSONException ex) {
Log.e("debug", ex.getMessage());
}
}
}
我的猜测是,我必须将数字放在引号中,但我必须以该格式保护数据(不带引号中的整数),并且我知道我的数据是有效的 JSON。
最佳答案
您正在拆分 JSONObject。因此 [{"lat": 47175650, "lon": 7637853}]
变成两个字符串 {"lat": 47175650
和 "lon": 7637853}
.
您的数据似乎存储为 JSONArray。因此,替换
locations = locations.substring(1, locations.length()-1);
String[] points = locations.split(",");
JSONObject json;
GeoPoint p;
try {
for (int i=0; i<points.length; i++) {
json = new JSONObject(points[i]);
// I guess the "getInt()"s here are the problem
p = new GeoPoint(json.getInt("lat"), json.getInt("lon"));
overlay.addItem(p, "location", "location");
}
} catch (JSONException ex) {
Log.e("debug", ex.getMessage());
}
与
try {
JSONArray array = new JSONArray(locations);
for(int i = 0; i < array.length(); i++) {
JSONObject json = array.getJSONObject(i);
GeoPoint p = new GeoPoint(json.getInt("lat"), json.getInt("lon"));
overlay.addItem(p, "location", "location");
}
} catch (JSONException ex) {
Log.e("debug", ex.getMessage());
}
关于java - java中从JSON数据获取整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26690130/