public static JSONObject post(String url,JSONObject json){
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
JSONObject response = null;
try {
StringEntity s = new StringEntity(json.toString());
s.setContentEncoding("UTF-8");
s.setContentType("application/json");
post.setEntity(s);
HttpResponse res = client.execute(post);
if(res.getStatusLine().getStatusCode() == HttpStatus.OK.value()){
HttpEntity entity = res.getEntity();
String charset = EntityUtils.getContentCharSet(entity);
response = new JSONObject(new JSONTokener(new InputStreamReader(entity.getContent(),charset)));
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return response;
}
如果你的内容没有嵌套关系,就全都是ojb.put(key, value);
如果有嵌套关系,就是 subObj=new JSONObject();obj.put(key, subObj);
如果需要数组,就用JSONArray 对象。
那么你需要的是:{header:{"code": -100, "message": {"title": "", "detail": ""}},body:{dataStores:{},parameters:{"args": ["menu_jw_pj_xspj_x", ">>"], "responseParam": "tooltip"}}}
这里面是有嵌套关系的,你先将其格式化,然后就知道嵌套关系了:
1
2
3
4
5
6
7
8
9
10
11
|
{
header : {
"code"
: -100,
"message"
: {
"title"
:
""
,
"detail"
:
""
}
}, body : {
dataStores : {}, parameters : {
"args"
: [
"menu_jw_pj_xspj_x"
,
">>"
],
"responseParam"
:
"tooltip"
}
}
};
|
注意方括号代表数组。
以前面为例:
JSONObject obj = new JSONObject();
JSONObject objHead = new JSONObject();
obj.put("head", objHead);
objHead.put("code", -100);
JSONObject objMsg = new JSONObject();
objHead.put("message", objMsg);
objMsg.put("title", "");
objMsg.put("detail", "");