Created
December 13, 2016 07:22
-
-
Save galcyurio/368856f4fbe94416738ea3fc71dfeac1 to your computer and use it in GitHub Desktop.
JSON 형태로 직렬화를 하게 되면 generic 관련 데이터나 다른 primitive type 데이터를 잃게 될 때의 대처방식
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package com.sds.gson; | |
| import java.lang.reflect.Type; | |
| import com.google.gson.Gson; | |
| import com.google.gson.reflect.TypeToken; | |
| public class GsonTest6_Generics_TypeToken { | |
| public GsonTest6_Generics_TypeToken() { | |
| Shape<Circle> shape = new Shape<Circle>(); | |
| Circle circle = new Circle(5.0); | |
| shape.setShape(circle); | |
| // Type 을 정의한다 | |
| Type shapeType = new TypeToken<Shape<Circle>>() {}.getType(); | |
| Gson gson = new Gson(); | |
| String json = gson.toJson(shape, shapeType); | |
| System.out.println("json = "+json); | |
| Shape shape1 = gson.fromJson(json, Shape.class); | |
| System.out.println(shape1.getShape().getClass()); | |
| System.out.println(shape1.getShape().toString()); | |
| System.out.println(shape1.getArea()); | |
| Shape shape2 = gson.fromJson(json, shapeType); | |
| System.out.println(shape2.getShape().getClass()); | |
| System.out.println(shape2.getShape().toString()); | |
| System.out.println(shape2.getArea()); | |
| } | |
| public static void main(String[] args) { | |
| new GsonTest6_Generics_TypeToken(); | |
| } | |
| } | |
| class Shape<T> { | |
| public T shape; | |
| public void setShape(T shape) { | |
| this.shape = shape; | |
| } | |
| public T getShape() { | |
| return shape; | |
| } | |
| public double getArea() { | |
| if (shape instanceof Circle) { | |
| return ((Circle) shape).getArea(); | |
| } else { | |
| return 0.0; | |
| } | |
| } | |
| } | |
| class Circle { | |
| private double radius; | |
| public Circle(double radius) { | |
| this.radius = radius; | |
| } | |
| public String toString() { | |
| return "Circle"; | |
| } | |
| public double getRadius() { | |
| return radius; | |
| } | |
| public void setRadius(double radius) { | |
| this.radius = radius; | |
| } | |
| public double getArea() { | |
| return (radius * radius * 3.14); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment