假设我已将以下对象序列化为json string:
class Person {
public final String name;
public Person(String name) { this.name = name; }
}
Person p = new Person("Bob Falaway");
JsonObject json = gson.toJsonTree(p, Person.class).getAsJsonObject();
现在我想反序列化它,但我想将名称拆分为两个字段firstName
和lastName
。我该怎么做?
我希望结果产生类似于:
的类class RefinedPerson {
public final String firstName;
public final String lastName;
public String toString() { return String.format("%s %s", firstName, lastName); }
}
Gson可以做到这一点吗?
答案 0 :(得分:2)
为类型注册自己的JsonSerializer
(如果您愿意,可以注册TypeAdapter
)?
类似的东西:
@JsonAdapter(PersonSerializer.class)
class Person {
private final String name;
Person(final String name) {
// Some validation...
this.name = name;
}
String getName() {
return this.name;
}
}
您的序列化程序看起来像:
class PersonSerializer implements JsonSerializer<Person> {
@Override
public JsonObject serialise(final Person src,
final Type personType,
final JsonSerializationContext context) {
final JsonObject json = new JsonObject();
final String[] names = src.getName().split(" ");
// Some validation...
json.addProperty("firstName", names[0]);
json.addProperty("lastName", names[1]);
return json;
}
}