代码。
Gson gson = new Gson();
// 1.
ClassA a = gson.fromJson(json, ClassA.class)
gson.fromJson(jsonB, a)// make jsonB to a
// 2.
ClassB b = new ClassB();
b.setXXX(xxx);
b.setYYY(yyy);
......
gson.fromJson(json, b)// make json to b
这可能吗?怎么样?
修改
// JSON A
{
"name":"wener"
}
// JSON B
{
"age":22
}
// CLASS A
class A
{
String name;
Integer age;
}
//
//
A a = gson.fromJson(JsonA, A.class)
// try to do somgthing like this
// this part is what I want to do.
gson.fromJson(JsonB, a)
// then
assert a.getName().equals("wener")
assert a.getAge().equals(22)
所以,只需要这样的东西。 fromJsonToInstance(String, Object);
答案 0 :(得分:0)
@Test
public void testMergeObject()
{
String jsonA = "{\"name\":\"wener\"}";
String jsonB = "{\"age\":22}";
Person person = new Person();
Gson gson = new GsonBuilder().registerTypeAdapter(Person.class, new InstanceCreatorWithInstance<>(person)).create();
gson.fromJson(jsonA, Person.class);
gson.fromJson(jsonB, Person.class);
assert person.getName().equals("wener");
assert person.getAge().equals(22);
}
@Data
static class Person
{
String name;
Integer age;
}
static class InstanceCreatorWithInstance<T> implements InstanceCreator<T>
{
T instance;
public InstanceCreatorWithInstance(T instance)
{
this.instance = instance;
}
@Override
public T createInstance(Type type)
{
return instance;
}
}
现在,我知道我想要做的是更改实例创建过程。