英文:
Create JSONObject inside JSONObject to post the data
问题
[
{
"message": {
"data": "E-Stop Off"
},
"platform": "ros",
"topic": "/android_app/nav_control",
"type": "std_msgs/String",
"expiration_secs": 1
}
]
我经常使用这种方法,但会有一些变化,这就是为什么我会将参数传递给这个方法。我无法在JSONObject内部添加另一个JSONObject。以下是我的努力:
public String postCommandJSON(JSONObject jsonObject, String topic, String type) {
JSONArray jsonArray = new JSONArray();
try {
JSONObject mainObject = new JSONObject();
mainObject.put("platform", "ros");
mainObject.put("topic", topic);
mainObject.put("type", type);
mainObject.put("expiration_secs", 1);
mainObject.put(jsonObject);
jsonArray.put(mainObject);
} catch (JSONException e) {
e.printStackTrace();
}
return jsonArray.toString();
}
在下面的代码中,我无法将一个JSONObject添加到另一个JSONObject中。
mainObject.put(jsonObject);
谢谢
英文:
I would like to create below JSON for the post in the body. I would like to build this JSON using the native class.
[
{
"message": {
"data": "E-Stop Off"
},
"platform": "ros",
"topic": "/android_app/nav_control",
"type": "std_msgs/String",
"expiration_secs": 1
}
]
I am using this method more often with few changes that is why I pass the argument in the method. I am not able to add JSONObject inside JSONObject. Here is my effort.
public String postCommandJSON(JSONObject jsonObject, String topic, String type) {
JSONArray jsonArray = new JSONArray();
try {
JSONObject mainObject = new JSONObject();
mainObject.put("platform", "ros");
mainObject.put("topic", topic);
mainObject.put("type", type);
mainObject.put("expiration_secs", 1);
mainObject.put(jsonObject);
jsonArray.put(mainObject);
} catch (JSONException e) {
e.printStackTrace();
}
return jsonArray.toString();
}
I am not able to add JSONObject inside JSONObject in below line.
> mainObject.put(jsonObject);
Thank you
答案1
得分: 0
假设在 mainObject.put(jsonObject);
处,您尝试创建类似以下内容的内容
{
"message": {
"data": "E-Stop Off"
}
...
}
除了值(将是JSON对象),您还需要通过key
将其传递给put
方法,以便我们以后能够访问该值。
所以您可能想将那行代码改为
mainObject.put("message", jsonObject);
并且如果元素的顺序很重要,甚至可能要在 mainObject.put("platform", "ros");
之前执行它。
英文:
Assuming that at mainObject.put(jsonObject);
you attempt to crate something along
{
"message": {
"data": "E-Stop Off"
}
...
}
then beside value (which will be JSON object) you also need to pass to put
method a key
via which we will later be able to access that value.
So you probably want to change that line into
mainObject.put("message", jsonObject);
and maybe even execute it before mainObject.put("platform", "ros");
if order of elements is important.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论