programing

GSON을 사용하여 Java 객체 직렬화

mailnote 2023. 3. 7. 21:46
반응형

GSON을 사용하여 Java 객체 직렬화

이 개체를 JSON String에 직렬화하고 싶습니다.

public class Person {
   public String id;
   public String name;
   public Person parent;
}

다음과 같은 결과를 얻을 수 있습니다.

{id: 1, name: "Joe", parent: 2}

사용하려고 했습니다.

Person p = new Person(1, "Joe", new Person(2, "Mike"));
Gson gson = new GsonBuilder()
            .registerTypeAdapter(Persona.class, new PersonSerializer()).create();
String str = gson.toJson(p);

하지만 그 대신, 나는 다음과 같은 것을 얻었다.

"1"

Person Serializer:

public class PersonSerializer implements JsonSerializer<Person> {
    public JsonElement serialize(Person src, Type typeOfSrc, ...) {
        return new JsonPrimitive(src.id);
    }
}

어떤 제안이라도 환영합니다

고마워, 마리오

원하는 결과를 얻으려면 시리얼라이저를 다음과 같이 기술해야 합니다.

public static class PersonSerializer implements JsonSerializer<Person> {
    public JsonElement serialize(final Person person, final Type type, final JsonSerializationContext context) {
        JsonObject result = new JsonObject();
        result.add("id", new JsonPrimitive(person.getId()));
        result.add("name", new JsonPrimitive(person.getName()));
        Person parent = person.getParent();
        if (parent != null) {
            result.add("parent", new JsonPrimitive(parent.getId()));
        }
        return result;
    }
}

결과

    Person p = new Person(1, "Joe", new Person(2, "Mike"));
    com.google.gson.Gson gson = new GsonBuilder().registerTypeAdapter(Person.class, new PersonSerializer())
            .create();
    System.out.println(gson.toJson(p));

될 것이다

{"id":1,"name":"Joe","parent":2}

완전한 코드:

import java.lang.reflect.Type;

import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

public class GsonSimpleTest {

    public static class Person {
        public int id;
        public String name;
        public Person parent;

        public Person(final int id, final String name) {
            super();
            this.id = id;
            this.name = name;
        }

        public Person(final int id, final String name, final Person parent) {
            super();
            this.id = id;
            this.name = name;
            this.parent = parent;
        }

        public int getId() {
            return id;
        }

        public void setId(final int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(final String name) {
            this.name = name;
        }

        public Person getParent() {
            return parent;
        }

        public void setParent(final Person parent) {
            this.parent = parent;
        }

    }

    public static class PersonSerializer implements JsonSerializer<Person> {
        public JsonElement serialize(final Person person, final Type type, final JsonSerializationContext context) {
            JsonObject result = new JsonObject();
            result.add("id", new JsonPrimitive(person.getId()));
            result.add("name", new JsonPrimitive(person.getName()));
            Person parent = person.getParent();
            if (parent != null) {
                result.add("parent", new JsonPrimitive(parent.getId()));
            }
            return result;
        }
    }

    public static void main(final String[] args) {
        Person p = new Person(1, "Joe", new Person(2, "Mike"));
        com.google.gson.Gson gson = new GsonBuilder().registerTypeAdapter(Person.class, new PersonSerializer())
                .create();
        System.out.println(gson.toJson(p));
    }

}

방금 정답을 맞혔어요.다만, @JsonAdapter 주석을 사용하여 다른 방법으로 공유하겠습니다.

퍼스널 빈에 이렇게 주석을 달았다.

@JsonAdapter(PersonAdatper.class)
public class Person {
    public int id;
    public String name;
    public Person parent;
}

커스텀 어댑터 생성

public  class PersonAdatper extends TypeAdapter<Person> {

    @Override
    public void write(JsonWriter writer, Person value) throws IOException {
        writer.beginObject();

        writer.name("id").value(value.getId());
        writer.name("name").value(value.getName());
        Person parent = value.getParent();
        if (parent != null) {
            writer.name("parent").value(parent.getId());
        }       
        writer.endObject();
    }

    @Override
    public Person read(JsonReader in) throws IOException {
        // do something you need
        return null;
    }

}

개체를 json 문자열로 직렬화합니다.

Person p = new Person(1, "Joe", new Person(2, "Mike"));
Gson gson = new Gson();    
String result = gson.toJson(p);

다음과 같은 출력이 생성됩니다.

{"id":1,"name":"Joe","parent":2}

JsonAdapter를 사용한 자습서 GSON 주석 예제에서 이 방법을 찾았습니다.

언급URL : https://stackoverflow.com/questions/11038553/serialize-java-object-with-gson

반응형