Java通过JSON数据中的键获取值

时间:2019-05-30 11:22:00

标签: java json

[
{
    "boylam":31.8039,
    "enlem":40.5906,
    "il":"",
    "ilPlaka":"",
    "ilce":"",
    "oncelik":0,
    "yukseklik":2052,
    "aciklama":"",
    "modelId":124774,
    "gps":0
}]

嗨,我手里有这样的JSON数据。我很难从这里取出数据。例如,如何在JSON数据中打印“ boylam”选项?

3 个答案:

答案 0 :(得分:0)

使用Google Gson,代码可能像这样:

    // construct the json object
    JsonArray jsonArray = new JsonArray();
    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("boylam",31.8039);
    jsonArray.add(jsonObject);
    // iterate the json array
    jsonArray.forEach(jsonElement -> {
        JsonObject element = (JsonObject) jsonElement;
        System.out.println(element.get("boylam"));
    });

答案 1 :(得分:0)

您可以使用JSON.simple将字符串数据转换为JSON对象。 https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple/1.1.1

public static void main(String[] args) throws ParseException {

    String data = "[\n" +
            "{\n" +
            "    \"boylam\":31.8039,\n" +
            "    \"enlem\":40.5906,\n" +
            "    \"il\":\"\",\n" +
            "    \"ilPlaka\":\"\",\n" +
            "    \"ilce\":\"\",\n" +
            "    \"oncelik\":0,\n" +
            "    \"yukseklik\":2052,\n" +
            "    \"aciklama\":\"\",\n" +
            "    \"modelId\":124774,\n" +
            "    \"gps\":0\n" +
            "}]";

    JSONParser parser = new JSONParser();

    JSONArray jsonArray = (JSONArray) parser.parse(data);

    JSONObject jsonObject = (JSONObject) jsonArray.get(0);

    System.out.println(jsonObject.get("boylam"));

}

答案 2 :(得分:0)

使用com.google.gson.Gson类,您可以做到这一点。

Gson gson= new Gson();

JSONObject json=new JSONObject();
json.put("boylam", "31.8039"); // this is your json object

Map map=gson.fromJson(json.toString(), Map.class);
System.out.println(map.get("boylam")); //ouput 31.8039