我有一个与网络服务连接的应用程序。我通过Json发送一些数据:
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("token", regId);
jsonObject.put("appId", GlobalConfig.getAPPLICATION_ID());
jsonObject.put("phoneId", 1);
JSONArray jArrayParam = new JSONArray();
jArrayParam.put(jsonObject);
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("Token",jArrayParam.toString()));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(GlobalConfig.getSendEmail());
httppost.addHeader("Authorization", "Basic " + Base64.encodeToString(
(GlobalConfig.getAuthString()).getBytes(),Base64.NO_WRAP));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePair, HTTP.UTF_8));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (Exception e) {
// TODO: handle exception
}
我怎样才能看到这个 json 的外观?我想服务器看到这样的东西:
{"Token": [
{
"token": "asdasfasf",
"appId": 8.8,
"phoneId": 142.369,
}
将 json 对象创建为:
JSONObject jsonObject = new JSONObject();
jsonObject.put("token", regId);
jsonObject.put("appId", GlobalConfig.getAPPLICATION_ID());
jsonObject.put("phoneId", 1);
JSONArray jArrayParam = new JSONArray();
jArrayParam.put(jsonObject);
JSONObject finaljsonobj = new JSONObject();
finaljsonobj.put("Token", jArrayParam);
现在finaljsonobj
JSON 对象如下所示:
{
"Token": [
{
"token": "asdasfasf",
"appId": 8.8,
"phoneId": 142.369,
}
]
}
使用 JSON.stringify(json_object)
.
让我们假设你的JSON实际上是有效的(它不是),并且你有一个功能完美的JSONObject。如果您想在控制台中看到它,只需执行以下操作:
System.out.println(myAwesomeJSONObject.toString(2));
该 1 表示缩进空格的数量。我喜欢它有 2 个缩进空格,但这是个人品味和可读性的问题。