Gson将字段转换为多个字段

时间:2017-07-25 23:05:04

标签: java json serialization gson

假设我已将以下对象序列化为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();

现在我想反序列化它,但我想将名称拆分为两个字段firstNamelastName。我该怎么做?

我希望结果产生类似于:

的类
class RefinedPerson {
    public final String firstName;
    public final String lastName;

    public String toString() { return String.format("%s %s", firstName, lastName); }
}

Gson可以做到这一点吗?

1 个答案:

答案 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;
    }
}