在JSONObject中创建JSONObject以发布数据

Arpit Patel:

我想在JSON下创建正文。我想使用本机类构建此JSON。

[
  {
    "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);

谢谢

Pshemo:

假设mainObject.put(jsonObject);您尝试沿箱包装东西

{
    "message": {
      "data": "E-Stop Off"
    }
    ...
}

然后在值(将是JSON对象)旁边,您还需要传递给put方法a key,我们以后将可以通过该方法访问该值。

所以你可能想把那条线改成

mainObject.put("message", jsonObject);

mainObject.put("platform", "ros");如果元素的顺序很重要,甚至可以在之前执行它

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

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

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章