如何构建的JSONObject请求HttpPost使用

问题描述:

我这里要说的是我需要建立一个例子:如何构建的JSONObject请求HttpPost使用

{ 
    "sendSmsRequest": { 
    "to": "5511982694404", 
    "msg": "funcionou" 
    } 
} 

为了做到这一点,我已经使用的JSONObject:

JSONObject jsonObject = new JSONObject(); 
jsonObject.put("to", "123456789"); 
jsonObject.put("msg", "Mensagem Teste"); 
StringEntity input = new StringEntity(jsonObject.toString()); 

这里要求:

post.setHeader("Accept", "application/json"); 
post.setHeader("Content-Type", "application/json"); 
post.setEntity(input); 

但我不知道如何把“头” - “sendSmsRequest” ...... 有什么办法这样做不使用字符串?

String teste = "{\"sendSmsRequest\": { \"to\": \"123456789\",\"msg\": \"funcionou\"}}"; 

你可以这样说:

JSONObject jsonObject = new JSONObject(); 
jsonObject.put("to", "123456789"); 
jsonObject.put("msg", "Mensagem Teste"); 
JSONObject jsonObject1 = new JSONObject(); 
jsonObject1.put("sendSmsRequest", jsonObject); 

StringEntity input = new StringEntity(jsonObject1.toString()); 

这样你就可以有一个JSONObject内的另一个JSONObject

+0

谢谢Moondaisy,这正是我需要的! –