简体   繁体   English

将具有json-format-string的对象序列化为json

[英]Serialize an object which has a json-format-string to json

I have an object like: 我有一个像这样的对象:

public class Foo{
  public String f1="[{\"jsonField\":\"something\"},{\"jsonField\":\"something\"}]";
}

Gson would serialize it to: Gson会将其序列化为:

{"f1":"[{\"jsonField\":\"something\"},{\"jsonField\":\"something\"}]"}

The f1 field was serialized to a string. f1字段已序列化为字符串。 Apparently, the field is a well formed json-format string. 显然,该字段是格式正确的json格式字符串。 How can I do to serialized the field to an jso array, like below: 如何将字段序列化为jso数组,如下所示:

{"f1":[{"jsonField":"something"},{"jsonField":"something"}]}

PS. PS。 For performance consideration, I can't deserialize then serialize the field. 出于性能考虑,我无法反序列化然后序列化该字段。

Gson is serializing your string field to a string. Gson正在将您的字符串字段序列化为字符串。 That's normal. 那很正常 If your field, however, was a List<String> , Gson would give you: 但是,如果您的字段是List<String> ,那么Gson会给您:

{"f1":["jsonField:something","jsonField:something"]}

And if it was a List where something has a field called jsonField you'd get what you actually want. 如果它是一个List,其中某些东西有一个名为jsonField的字段, jsonField您将得到真正想要的。

This is the implicit way that Gson serializes your objects. 这是Gson序列化对象的隐式方式。 If you don't like it, you need to implement your own TypeAdapter and register it with Gson at the builder. 如果您不喜欢它,则需要实现自己的TypeAdapter并在构建器处向Gson注册。

GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(MyObject.class, new SomethingGsonAdapter());
Gson gson = builder.create()

And you need to define: 您需要定义:

public class SomethingGsonAdapter implements JsonDeserializer<DataItem>, JsonSerializer<DataItem>;

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

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