简体   繁体   English

Gson JsonObject全局变量

[英]Gson JsonObject global variable

I'm using Gson API and created a class like: 我正在使用Gson API并创建了一个类:

public class Person
{
   private String name;
   private JsonObject someInfo;

   public Person()
   {
   }
}

When I serealize an instance of this class using: 当我使用以下方法实现此类的实例时:

Person person = new Person();
person.name = "Charles"
person.someInfo = new JsonObject();
person.someInfo.addProperty("key1","value1");
Gson gson = new Gson();
String jsonStr = gson.toJson(person);

I get the info inside a members properties: 我在成员属性中获取信息:

{"members":{"name":"Charles","someInfo":{"key1":"value1"}}}

I've noticed that if I declare the Person's class someInfo global variable as JsonElement instead of JsonObject the info is displayed correctly. 我注意到如果我将Person的类someInfo全局变量声明为JsonElement而不是JsonObject,则信息会正确显示。

Is there any way to serealize the information using JsonObject? 有没有办法使用JsonObject实现信息?

What I expect is: 我的期望是:

{"name":"Charles","someInfo":{"key1":"value1"}}

I was having the same problem using Gson 2.2.2. 我使用Gson 2.2.2时遇到了同样的问题。

When I upgraded to Gson 2.2.3, I got the expected JSON when I serialized JsonObject. 当我升级到Gson 2.2.3时,我在序列化JsonObject时得到了预期的JSON。

Use a Map for your someInfo: 为someInfo使用Map:

public class Person
{
   private String name;
   private Map<Object, Object> someInfo;

   public Person()
   {
   }

}

Person person = new Person();
person.name = "Charles";
person.someInfo = new HashMap<Object, Object>();
person.someInfo.put("key1","value1");

Although it would be better to use proper getters/setters to access Person variables. 虽然使用适当的getter / setter来访问Person变量会更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM