如何映射JSONObject-找不到JSONObject [“ id”]

时间:2019-08-18 13:25:59

标签: json

我无法从下面的json检索字段customer.id的信息: {“ date”:“ 2019-10-29T21:34:07.391Z”,“ customer”:{“ id”:“ 9999999999999999999”}}

我尝试将客户映射为JSONObject并获取键“ id”,但没有用 我尝试将客户映射为JSONObject,将ID映射为JSONObject,但是没有用

JSONObject json = new JSONObject("{\"customer\":{\"id\":\"9999999999999999999\"},\"date\":\"2019-10-29T21:34:07.391Z\"}");
JSONObject customer = new JSONObject(json.get("customer"));

// Show full string
System.out.println(json);
// Date returned without problems
System.out.println("date: "+json.get("date"));
// Customer object returend without problems
System.out.println("customerObject"+json.get("customer"));

// Trying to extract info - both failed
try{
    System.out.println("customerId: "+customer.getString("id"));
} catch (JSONException e){
    System.out.println("getString(id) failed: "+e.toString());
}
try{
    JSONObject id = new JSONObject(customer.get("id"));
} catch (JSONException e){
    System.out.println("customer.get(id) failed: "+e.toString());
}

ER:

{"date":"2019-10-29T21:34:07.391Z","customer":{"id":"9999999999999999999"}}
date: 2019-10-29T21:34:07.391Z
customerObject{"id":"9999999999999999999"}
customerId: 9999999999999999999

AR:

{"date":"2019-10-29T21:34:07.391Z","customer":{"id":"9999999999999999999"}}
date: 2019-10-29T21:34:07.391Z
customerObject{"id":"9999999999999999999"}
getString(id) failed: org.json.JSONException: JSONObject["id"] not found.
customer.get(id) failed: org.json.JSONException: JSONObject["id"] not found.

1 个答案:

答案 0 :(得分:0)

尝试: 创建JSONObject customer时,添加toString()

JSONObject json = new JSONObject("{\"customer\":{\"id\":\"9999999999999999999\"},\"date\":\"2019-10-29T21:34:07.391Z\"}");
JSONObject customer = new JSONObject(json.get("customer").toString());

// Show full string
System.out.println(json);
// Date returned without problems
System.out.println("date: "+json.get("date"));
// Customer object returend without problems
System.out.println("customerObject"+json.get("customer"));

// Trying to extract info - both failed
try{
    System.out.println("customerId: "+customer.getString("id"));
} catch (JSONException e){
    System.out.println("getString(id) failed: "+e.toString());
}
try{
    JSONObject id = new JSONObject(customer.get("id"));
} catch (JSONException e){
    System.out.println("customer.get(id) failed: "+e.toString());
}