使用JSONObject生成JSON时为何出现多余nameValuePairs字段?
问题:生成JSON时出现多余的
nameValuePairs字段 需求目标
需要生成的JSON格式如下:
{ "data": { "data": "message" }, "status": "SUCCESS" }
实现代码
使用以下代码动态生成JSON:
JSONObject jsonObject = new JSONObject(); JSONObject jsonData = new JSONObject(); try { jsonData.put("data", "message"); jsonObject.put("data",jsonData); jsonObject.put("status", "SUCCESS"); Log.d("AYadav", new Gson().toJson(jsonObject)); } catch (JSONException e) { e.printStackTrace(); }
实际结果
运行后得到的JSON包含多余的nameValuePairs字段:
{ "nameValuePairs": { "data": { "nameValuePairs": { "data": "message" } }, "status": "SUCCESS" } }
原因分析
你这里混用了org.json.JSONObject(Android原生或Java的org.json库)和Gson的序列化方法:
- org.json.JSONObject内部是用
nameValuePairs这个Map来存储所有键值对的,它本身没有给Gson提供适配的序列化规则。 - 当调用Gson的
toJson()方法序列化org.json.JSONObject对象时,Gson会默认把对象的所有成员变量都序列化出来,自然就包含了内部的nameValuePairs字段。
解决方案
推荐三种可行的解决方式:
1. 全程使用Gson的JsonObject构建
直接用Gson提供的JsonObject来构建数据,避免混合使用不同JSON库:
JsonObject jsonData = new JsonObject(); jsonData.addProperty("data", "message"); JsonObject jsonObject = new JsonObject(); jsonObject.add("data", jsonData); jsonObject.addProperty("status", "SUCCESS"); Log.d("AYadav", new Gson().toJson(jsonObject));
2. 使用org.json的toString()方法输出
如果坚持用org.json.JSONObject,直接调用它自带的toString()方法就能得到正确格式的JSON:
JSONObject jsonObject = new JSONObject(); JSONObject jsonData = new JSONObject(); try { jsonData.put("data", "message"); jsonObject.put("data",jsonData); jsonObject.put("status", "SUCCESS"); Log.d("AYadav", jsonObject.toString()); // 改用toString() } catch (JSONException e) { e.printStackTrace(); }
3. 用Gson的toJsonTree处理
如果需要用Gson做后续处理,可以先把org.json.JSONObject转成Gson的JsonElement:
JSONObject jsonObject = new JSONObject(); JSONObject jsonData = new JSONObject(); try { jsonData.put("data", "message"); jsonObject.put("data",jsonData); jsonObject.put("status", "SUCCESS"); Gson gson = new Gson(); JsonElement jsonElement = gson.toJsonTree(jsonObject.toMap()); // 转成Map再处理 Log.d("AYadav", gson.toJson(jsonElement)); } catch (JSONException e) { e.printStackTrace(); }
内容的提问来源于stack exchange,提问作者Amit Yadav
相关产品推荐
相关产品推荐

