Java中JSON生成的额外支持

时间:2017-08-30 22:58:34

标签: android json

我正在尝试生成以下JSON

     {
       "mobileTerminate" : {
        "message" : {
          "content" : "Hello",
            "type" : "text"
            },
             "destination" : {
              "address" : "12125551212"
          }
        }
      }

我有以下代码:

                JSONObject jsonData = new JSONObject();
                JSONObject mobileObject = new JSONObject();
                JSONObject messageObject = new JSONObject();
                JSONObject destinationObject = new JSONObject();


                try {
                    Log.d("AAA", "in json try");
                    //messageObject.put("message", "");
                    messageObject.put("content", "Hello");
                    messageObject.put("type", "text");
                    destinationObject.put("address", "12125551212");

                    jsonData.put("MobileTerminate", mobileObject.toString() );
                    jsonData.put("message", messageObject.toString());
                    jsonData.put("destination", destinationObject.toString());
               }

这会生成以下JSON:

  {"MobileTerminate":"{}",
        "message":"
         {\"content\":\"Hello\",\"type\":\"text\"}",
          "destination":"
         {\"address\":\"12125551212\"}"}

忽略\逃脱。生成的JSON有几个问题:

        1. The extra } after MobileTerminate : {
        2. Are the commas legal?

如何更新代码以使生成的JSON与原始JSON类似?

2 个答案:

答案 0 :(得分:1)

在创建toString()时删除所有JSONObject来电:

jsonData.put("MobileTerminate", mobileObject );
jsonData.put("message", messageObjectg());
jsonData.put("destination", destinationObject);

如果您需要字符串表示,那么一旦添加了所需的所有元素,只需在最终toString()对象上调用jsonData

Log.d("Works", jsonData.toString());

修改

  

JSON应该以{MobileTerminate:{....开头,而不是{MobileTerminate:{}

这是因为你没有把任何东西放进mobileObject所以它只是空的。您需要添加如下内容:

mobileObject.put("message", messageObjectg());
mobileObject.put("destination", destinationObject);    
jsonData.put("MobileTerminate", mobileObject );

答案 1 :(得分:1)

试试这个,

JSONObject jsonData = new JSONObject();
JSONObject mobileObject = new JSONObject();
JSONObject messageObject = new JSONObject();
JSONObject destinationObject = new JSONObject();
try {
    messageObject.put("content", "Hello");
    messageObject.put("type", "text");
    destinationObject.put("address", "12125551212");

    mobileObject.put("message", messageObject);
    mobileObject.put("destination", destinationObject);

    jsonData.put("mobileTerminate", mobileObject);
    Log.d("TAG", "@@@ json :"+jsonData);
}
catch (Exception e){}