2017-08-29 74 views
1

我有,我想发送到服务器POST如何在Android的JSON中包含层次结构?

{ 
    "header1" : { 
     "message" : { 
      "content" : "Hello", 
      "type" : "text" 
     }, 
     "header2" : { 
      "address" : "[email protected]" 
     } 
    } 
} 

这是我对JSON pbject 的JSONObject的JSONObject =新的JSONObject()代码这个JSON文件;

  jsonObject.put("content", "hello"); 
      jsonObject.put("type", "text"); 
      jsonObject.put("address", "[email protected]"); 
      String message = jsonObject.toString(); 

我的问题是如何编码层次结构:header1,message和header2?

回答

0

我想你应该在自下而上时尚。

我的意思是首先制作一个名为header2的JSONObject并将其放入address

然后让对方的JSONObject命名为message,填充它使用put,然后又将它的地方另一个里面的JSONObject命名header1

JSONObject header2 = new JSONObject(); 
header2.put("address", "your address"); 

然后,

JSONObject header1 = new JSONObject(); 
header1.put("header2", header2); 

等等......

1
JSONObject json = new JSONObject(); 
    JSONObject messageObject = new JSONObject(); 
    JSONObject header2Object = new JSONObject(); 
    try { 

     messageObject .put("content", "Hello"); 
     messageObject .put("type", "text"); 

     header2Object .put("address", "[email protected]"); 

     json.put("header1", messageObject.tostring); 
     json.put("header2", header2Object.tostring); 
    } catch (Exception ignored) { 
    } 

试试这个