JSON嵌套在POJO中

我有一个POJO课程:

public class D{ private JSONObject profileData; public JSONObject getProfileData () { return profileData; } public void setProfileData (JSONObject profileData) { this.profileData = profileData; } } 

现在我填充这个类,如:

 for (int i =0; i<identities.size();i++){ D d = new D(); d.setProfileData(profileData); dList.add(d); } 

我使用HashMap从GSON为profileData创建JSON对象:

 profileDataInJson = new JSONObject(gson.toJson(map1)); 

profileDataInJson的签名是: JSONObject profileDataInJson = null;

现在生成的JSON就像:

 "profileData":{"map":{"ioCinema":"firstValue","ioSIMAvailable":"firstKey","Name":"onePair"}} 

其中我在主profileData对象中插入了一个名为map的不需要的对象。

但是,当我在循环内打印时,我得到了

 {`"ioCinema":"firstValue","ioSIMAvailable":"firstKey","Name":"onePair"}` 

Whish正是我想要的profileData对象,没有嵌套map对象。

我该如何解决这个问题?

“我已经意识到我可以通过将D类中的profileData类型从JSONObject转换为String来实现这一点,这将导致转义字符 – 但我正在寻找一个通用的解决方案”

编辑:

map1有两种构造方式,具体取决于用户输入,两种方式如下:

 if (args.length >= 4 && args[1].equalsIgnoreCase("onePair")) { map1 = new HashMap(); String key1 = args[2]; String value1 = args[3]; map1.put(key1, value1); profileDataInJson = new JSONObject(gson.toJson(map1)); } 

和:

 if (args.length >= 1 && args[0].equalsIgnoreCase("update")) { if (args.length >= 2) profileData.setName(args[1] != null ? args[1] : ""); if (args.length >= 3) profileData.setSIMAvailable(args[2] != null ? args[2] : ""); profileDataInJson = new JSONObject(profileData); } 

签名: ProfileData profileData = new ProfileData();

令我困惑的是当我尝试遍历profileData并尝试通过名称“map”获取json对象时,我得到一个nullPointerexception

您不需要使用Gson将hashmap转换为json对象。 只需使用:

profileDataInJson = new JSONObject(map);

将自定义序列化程序添加到Gson,以便Gson按照您的预期序列化组织JSON。

 GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(JSONObject.class, new JsonSerializer() { @Override public JsonElement serialize(final JSONObject src, final Type typeOfSrc, final JsonSerializationContext context) { return new JsonParser().parse(src.toString()).getAsJsonObject(); } }); gsonBuilder.create().toJson(map1); 

这将返回{"ioCinema":"firstValue","ioSIMAvailable":"firstKey","Name":"onePair"}