JSON字符串中的Java访问数据

时间:2017-04-20 17:57:28

标签: java json parsing

我在访问JSON字符串中的数据时遇到问题。我做错了什么?

工作:

void print(struct dog *list){

    /* Prints all structs within the
     * linked list
     */


    printf("\nID Number\t Dog Name\t Breed\t\t Owner\n");
    for( ; list != NULL; list = list->next){

            printf("%d\t\t  %-10s\t  %-10s\t %-12s\n", list->number, list->dog_name, list->breed, list->owner_last_name);

    }

不工作:

JSONObject obj = new JSONObject("JSON-STRING");
JSONArray arr = obj.getJSONArray("weather");
System.out.println(arr.getJSONObject(0).get("description"); >> clear sky

例外:

JSONObject obj = new JSONObject("JSON-STRING");
JSONArray arr = obj.getJSONArray("main");
System.out.println(arr.getJSONObject(0).get("temp"); >> 285.15

JSON-String:

org.json.JSONException: JSONObject["main"] is not a JSONArray.
    at org.json.JSONObject.getJSONArray(JSONObject.java:622)
    at main.SmartHomeBot.onUpdateReceived(SmartHomeBot.java:47)
    at org.telegram.telegrambots.updatesreceivers.DefaultBotSession$HandlerThread.run(DefaultBotSession.java:274)

3 个答案:

答案 0 :(得分:1)

您收到错误,因为weather是多个weather的数组,而main是单个对象。

两者之间的差异如下所示:

 "weather": [{
        "id": 800,
        "main": "Clear",
        "description": "clear sky",
        "icon": "01d"
    }
],

"main": {
    "temp": 285.15,
    "pressure": 1034,
    "humidity": 30,
    "temp_min": 285.15,
    "temp_max": 285.15
},

因此,在JSON "weather" : [{....}, {....}, {....}] []中显示weather是数组。

答案 1 :(得分:0)

在密钥"天气"的父亲json值中表示一个JSONArray,但键值为#34; main"表示JSONObject而不是JSONArray。

要从JsonObject获取数据,您应该执行以下操作

JSONObject mainObj = obj.getJSONObject("main");
System.out.println(mainObj.get("temp"));

答案 2 :(得分:0)

String jsonobj = "{\n    \"coord\": {\n        \"lon\": 6.55,\n        \"lat\": 51.27\n    },\n    \"weather\": [{\n            \"id\": 800,\n            \"main\": \"Clear\",\n            \"description\": \"clear sky\",\n            \"icon\": \"01d\"\n        }\n    ],\n    \"base\": \"stations\",\n    \"main\": {\n        \"temp\": 285.15,\n        \"pressure\": 1034,\n        \"humidity\": 30,\n        \"temp_min\": 285.15,\n        \"temp_max\": 285.15\n    },\n    \"visibility\": 10000,\n    \"wind\": {\n        \"speed\": 2.6\n    },\n    \"clouds\": {\n        \"all\": 0\n    },\n    \"dt\": 1492705200,\n    \"sys\": {\n        \"type\": 1,\n        \"id\": 4909,\n        \"message\": 0.2825,\n        \"country\": \"DE\",\n        \"sunrise\": 1492662386,\n        \"sunset\": 1492713582\n    },\n    \"id\": 2808559,\n    \"name\": \"Willich\",\n    \"cod\": 200\n}";
JSONObject obj = new JSONObject(jsonobj);
JSONObject jsonObject = obj.getJSONObject("main");
System.out.println(jsonObject.get("temp"));