2017-10-16 98 views
-3

我想讀取JSON,但我得到一些錯誤,因爲這有一個「子對象」內的JSON。使用org.json閱讀Json

{ 
    "orders": [{ 
     "code": "foo", 
     "channel": "foo", 
     "placed_at": "foo", 
     "updated_at": "foo", 
     "total_ordered": 000.00, 
     "interest": 0.0, 
     "discount": 0.0, 
     "shipping_cost": 0.0, 
     "shipping_method": "foo", 
     "estimated_delivery": "foo", 
     "estimated_delivery_shift": null, 
     "shipping_address": { 
     "full_name": "Test", 
     "street": "address", 
     "number": "00", 
     "detail": "foo", 
     "neighborhood": "foo", 
     "city": "foo", 
     "region": "foo", 
     "country": "foo", 
     "postcode": "foo", 
     "phone": "foo", 
     "secondary_phone": "foo" 
    }] 
    } 

當我嘗試讀取裏面的 「shipping_address」 元素, 我得到這個錯誤: 「的getString

Exception in thread "main" org.json.JSONException: JSONObject["shipping_address"] is not a JSONArray. 
at org.json.JSONObject.getJSONArray(JSONObject.java:623) 
at br.com.ibolt.tdd.JsonRead.main(JsonRead.java:44) 

使用 」getJSONObject(「 shipping_address)解決(」 FULL_NAME 「)」 感謝你@djbrown

+0

好吧,這顯然不是一個數組...使用正確的方法獲取對象 –

+0

使用'JSONObject.getJSONObject(String name)' –

+1

'shipping_address' - 'JSONObject','orders' - 'JSONArray' – Pijotrek

回答

0

正確的JSON是:

{ 
    "orders": [{ 
     "code": "foo", 
     "channel": "foo", 
     "placed_at": "foo", 
     "updated_at": "foo", 
     "total_ordered": "000.00", 
     "interest": 0.0, 
     "discount": 0.0, 
     "shipping_cost": 0.0, 
     "shipping_method": "foo", 
     "estimated_delivery": "foo", 
     "estimated_delivery_shift": null, 
     "shipping_address": { 
      "full_name": "Test", 
      "street": "address", 
      "number": "00", 
      "detail": "foo", 
      "neighborhood": "foo", 
      "city": "foo", 
      "region": "foo", 
      "country": "foo", 
      "postcode": "foo", 
      "phone": "foo", 
      "secondary_phone": "foo" 
     } //missing 
    }]  
} 

你錯過了一個支撐。

我也認爲字段"total_ordered"應該有雙引號。

0

您的JSON是無效

「shipping_address」:{< ===沒有關閉

正確的是:

{ 
    "orders": [ 
    { 
     "code": "foo", 
     "channel": "foo", 
     "placed_at": "foo", 
     "updated_at": "foo", 
     "total_ordered": 000.00, 
     "interest": 0.0, 
     "discount": 0.0, 
     "shipping_cost": 0.0, 
     "shipping_method": "foo", 
     "estimated_delivery": "foo", 
     "estimated_delivery_shift": null, 
     "shipping_address": { 
     "full_name": "Test", 
     "street": "address", 
     "number": "00", 
     "detail": "foo", 
     "neighborhood": "foo", 
     "city": "foo", 
     "region": "foo", 
     "country": "foo", 
     "postcode": "foo", 
     "phone": "foo", 
     "secondary_phone": "foo" 
     } 
    } 
    ] 
}