我想在Java中使用JSON对象生成2d JSON数组。我正在尝试生成以下JSON。在Java中生成2d Json数组
的Java代码..
JSONObject root = new JSONObject();
JSONObject c0 = new JSONObject();
JSONObject c1 = new JSONObject();
JSONObject attachment = new JSONObject();
JSONObject payload = new JSONObject();
JSONObject buttons = new JSONObject();
root.put("recipient", c0);
root.put("message", c1);
c0.put("id", userId);
c1.put("message", attachment);
attachment.put("type", "template");
attachment.put("payload", payload);
payload.put("template_type", "button");
payload.put("text", "What do you want to do next");
payload.put("buttons", buttons);
buttons.put("type", "web_url");
buttons.put("url", "https://google.com");
buttons.put("title", "show website");
buttons.put("type", "postback");
buttons.put("title", "Hi There");
buttons.put("payload", "sample payload");
预期JSON输出 ..
{
"recipient":{
"id":"USER_ID"
},
"message":{
"attachment":{
"type":"template",
"payload":{
"template_type":"button",
"text":"What do you want to do next?",
"buttons":[
{
"type":"web_url",
"url":"https://google.com",
"title":"Show Website"
},
{
"type":"postback",
"title":"Start Chatting",
"payload":"Sample_PAYLOAD"
}
]
}
}
}
}
电流输出 ..
{
"recipient":{"
id":"988459377921053"
},
"message":{
"message":{"
payload":{
"buttons":{
"payload":"sample payload",
"type":"postback",
"title":"Hi There",
"url":"https://google.com"
},
"template_type":"button",
"text":"What do you want to do next"},
"type":"template"
}
}
}
我创建嵌套的JSON对象和从外部添加它们仍然内在层面仍然输出JSON不是预期的。无法理解我要出错的地方。
编辑1:
产生由用户@ user1802604但JSON提到试图改变是以下格式的..
{
"recipient":{
"id":"988459377921053"
},
"message":{
"attachment":{
"payload":{
"buttons":[
{
"payload":"sample payload",
"type":"postback",
"title":"Hi There",
"url":"https://google.com"
},
{
"payload":"sample payload",
"type":"postback",
"title":"Hi There",
"url":"https://google.com"
}
],
"template_type":"button",
"text":"What do you want to do next"
},
"type":"template"
}
}
}
该API到我发送JSON被返回带有“错误请求”消息的响应代码400。有没有办法保持元素的顺序?
'的JSONObject按钮=新的JSONObject();'应该是一个'JSONArray'保持'JSONObject' – AxelH