【问题标题】:Parsing a json (string & float) file with java用java解析一个json(字符串和浮点数)文件
【发布时间】:2018-01-16 15:09:43
【问题描述】:

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

我的json file 看起来像这样:

{“11​​542”:[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]);
}

}

【问题讨论】:

  • 请给我们你自己的尝试,你想达到什么目的
  • 那个json的格式真的不好

标签: java json parsing gson deserialization


【解决方案1】:

使用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】:

    这里有几篇文章可以帮助您解决问题。

    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/

    【讨论】:

    【解决方案3】:

    您应该在问题中添加更多详细信息。 无论如何,您可以使用简单的 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
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2013-02-27
      • 1970-01-01
      • 2015-03-15
      • 2021-06-30
      • 1970-01-01
      • 1970-01-01
      • 2022-01-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多