Question

code first.

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

Is this possible ? how ?

EDIT

// 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)

So, just need something like this. fromJsonToInstance(String, Object);

Was it helpful?

Solution

@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;
    }
}

Now, I know what I want to do is change the instance creation process.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top