如何映射 JSONObject - 未找到 JSONObject["id"]

拉斐尔·拉塞尔达·德·卡尔达斯

我无法从下面的 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());
}

是:

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

和:

{"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.
梅尔·凯勒

试试这个:创建时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());
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章