使用java解析json(string& float)文件

时间:2018-01-16 15:09:43

标签: java json parsing gson deserialization

我的目标是parse一个带有Java的json文件。

我的json file看起来像这样:

  

{" 11542":[40.870932001722714,-73.62889780791781]," 54548":   [45.859817510232425,-89.82102639934573]," 11547":[40.83072033793459,   -73.6445076194238]}

我想做的是able to input the zip code(字符串)并获得coordinates as outcome

谢谢

编辑:

TypeToken帮了很多!!

public class ZipCodeLookup {

public class ZipCodeResult {

    final double longitude;
    final double latitude;

    public ZipCodeResult(double longitude, double latitude) {
        this.longitude = longitude;
        this.latitude = latitude;
    }

    public double getLongitude() {
        return longitude;
    }

    public double getLatitude() {
        return latitude;
    }

}

public Map<String, Double[]> lookups;

public ZipCodeLookup(InputStream is) throws IOException {
    Gson gson = new Gson();
    Reader reader = new InputStreamReader(is);
    lookups = gson.fromJson(reader, new TypeToken<Map<String, Double[]>>() {
    }.getType());

    reader.close();
}

public ZipCodeResult lookupZipcode(String zipcode) {
    Double[] values = lookups.get(zipcode);
    return (values == null) ? null : new ZipCodeResult(values[0], values[1]);
}

}

3 个答案:

答案 0 :(得分:0)

这里有几篇帖子可以帮助您解决问题。

How to parse JSON

编辑:

根据您的评论。这是一个简单的例子(未经测试)

String str = "{yourJson}";
JSONObject obj = new JSONObject(str);
JSONArray arr = obj.getJSONArray("zip-code");
arr.getDouble(0); // Coordinate X
arr.getDouble(1); // Coordinate Y

http://theoryapp.com/parse-json-in-java/

答案 1 :(得分:0)

使用json.org,您可以轻松访问以下数据:

    JSONObject json= new JSONObject(string); //String is the json you want to parse
    int firstNumber=json.getJSONArray("11542").getInt(0); //11542 is the zip code you want to access
    int secondNumber=json.getJSONArray("11542").getInt(1);

答案 2 :(得分:0)

您应该在问题中添加更多详细信息。 无论如何,您可以使用简单的JSON,然后使用以下代码:

JSONParser parser = new JSONParser();

try {
    JSONObject jsonObject = (JSONObject)parser.parse("{\"11542\": [40.870932001722714, -73.62889780791781], \"54548\": [45.859817510232425, -89.82102639934573], \"11547\": [40.83072033793459, -73.6445076194238]}");  
    JSONArray coords = (JSONArray) jsonObject.get(zipCode);
    Iterator<Double> iterator = coords.iterator();
    while (iterator.hasNext()) {
     System.out.println(iterator.next());
    }        
} catch (ParseException e) {
    e.printStackTrace();
}

当然你必须传递正确的zipCode。如果这样做,您应该看到以下结果:

40.870932001722714
-73.62889780791781

希望,这有帮助