首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何映射JSONObject - JSONObject["id"]未找到

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

Stack Overflow用户
提问于 2019-08-18 21:25:59
回答 1查看 499关注 0票数 0

无法从下面的json中获取customer.id字段的信息:{"date":"2019-10-29T21:34:07.391Z","customer":{"id":"9999999999999999999"}}

我尝试将客户映射为JSONObject并获取关键字" id“,但不起作用我尝试将客户映射为JSONObject,将id映射为JSONObject,但不起作用

代码语言:javascript
复制
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());
}

急诊室:

代码语言:javascript
复制
{"date":"2019-10-29T21:34:07.391Z","customer":{"id":"9999999999999999999"}}
date: 2019-10-29T21:34:07.391Z
customerObject{"id":"9999999999999999999"}
customerId: 9999999999999999999

AR:

代码语言:javascript
复制
{"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.
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-08-18 21:57:21

试试这个:在创建JSONObject customer时添加toString()

代码语言:javascript
复制
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());
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57545011

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档