UFO ET IT

Gson :지도를 직렬화하는 더 쉬운 방법이 있습니까?

ufoet 2020. 12. 26. 15:47
반응형

Gson :지도를 직렬화하는 더 쉬운 방법이 있습니까?


Gson 프로젝트 의이 링크는 형식화 된 Map을 JSON으로 직렬화하기 위해 다음과 같은 작업을 수행해야 함을 나타내는 것 같습니다.

    public static class NumberTypeAdapter 
      implements JsonSerializer<Number>, JsonDeserializer<Number>,
InstanceCreator<Number> {

    public JsonElement serialize(Number src, Type typeOfSrc, JsonSerializationContext
context) {
      return new JsonPrimitive(src);
    }

    public Number deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context)
        throws JsonParseException {
      JsonPrimitive jsonPrimitive = json.getAsJsonPrimitive();
      if (jsonPrimitive.isNumber()) {
        return jsonPrimitive.getAsNumber();
      } else {
        throw new IllegalStateException("Expected a number field, but was " + json);
      }
    }

    public Number createInstance(Type type) {
      return 1L;
    }
  }

  public static void main(String[] args) {
    Map<String, Number> map = new HashMap<String, Number>();    
    map.put("int", 123);
    map.put("long", 1234567890123456789L);
    map.put("double", 1234.5678D);
    map.put("float", 1.2345F);
    Type mapType = new TypeToken<Map<String, Number>>() {}.getType();

    Gson gson = new GsonBuilder().registerTypeAdapter(Number.class, new
NumberTypeAdapter()).create();
    String json = gson.toJson(map, mapType);
    System.out.println(json);

    Map<String, Number> deserializedMap = gson.fromJson(json, mapType);
    System.out.println(deserializedMap);
  }

멋지고 작동하지만 너무 많은 오버 헤드 ( 전체 유형 어댑터 클래스? ) 처럼 보입니다 . JSONLib와 같은 다른 JSON 라이브러리를 사용했으며 다음과 같은 방법으로지도를 작성할 수 있습니다.

JSONObject json = new JSONObject();
for(Entry<String,Integer> entry : map.entrySet()){
     json.put(entry.getKey(), entry.getValue());
}

또는 다음과 같은 사용자 지정 클래스가있는 경우 :

JSONObject json = new JSONObject();
for(Entry<String,MyClass> entry : map.entrySet()){
 JSONObject myClassJson =  JSONObject.fromObject(entry.getValue());
     json.put(entry.getKey(), myClassJson);
}

이 프로세스는 더 수동적이지만 코드가 덜 필요하며 Number 또는 대부분의 경우 내 사용자 정의 클래스 에 대한 사용자 정의 유형 어댑터를 작성하는 데 드는 오버 헤드가 없습니다 .

이것이 Gson으로 맵을 직렬화하는 유일한 방법입니까, 아니면 위의 링크에서 Gson이 권장하는 것을 능가하는 방법을 찾은 사람이 있습니까?


TypeToken부품 만 필요합니다 (제네릭이 관련된 경우).

Map<String, String> myMap = new HashMap<String, String>();
myMap.put("one", "hello");
myMap.put("two", "world");

Gson gson = new GsonBuilder().create();
String json = gson.toJson(myMap);

System.out.println(json);

Type typeOfHashMap = new TypeToken<Map<String, String>>() { }.getType();
Map<String, String> newMap = gson.fromJson(json, typeOfHashMap); // This type must match TypeToken
System.out.println(newMap.get("one"));
System.out.println(newMap.get("two"));

산출:

{"two":"world","one":"hello"}
hello
world

기본

Map 직렬화의 기본 Gson 구현은 toString()키에서 사용 합니다.

Gson gson = new GsonBuilder()
        .setPrettyPrinting().create();
Map<Point, String> original = new HashMap<>();
original.put(new Point(1, 2), "a");
original.put(new Point(3, 4), "b");
System.out.println(gson.toJson(original));

줄게:

{
  "java.awt.Point[x\u003d1,y\u003d2]": "a",
  "java.awt.Point[x\u003d3,y\u003d4]": "b"
}


사용 enableComplexMapKeySerialization

기본 Gson 규칙에 따라 맵 키를 직렬화하려면 enableComplexMapKeySerialization 을 사용할 수 있습니다 . 그러면 키-값 쌍의 배열이 반환됩니다.

Gson gson = new GsonBuilder().enableComplexMapKeySerialization()
        .setPrettyPrinting().create();
Map<Point, String> original = new HashMap<>();
original.put(new Point(1, 2), "a");
original.put(new Point(3, 4), "b");
System.out.println(gson.toJson(original));

반환 :

[
  [
    {
      "x": 1,
      "y": 2
    },
    "a"
  ],
  [
    {
      "x": 3,
      "y": 4
    },
    "b"
  ]
]

자세한 내용은 여기에서 확인할 수 있습니다 .


나는 GSON이지도와 다중 중첩지도 (즉 Map<String, Map<String, Object>>)를 기본적으로 직렬화 / 제거 할 것이라고 확신 합니다. 내가 생각하는 예제는 더 복잡한 작업을 수행해야하는 경우 시작점 일뿐입니다.

Check out the MapTypeAdapterFactory class in the GSON source: http://code.google.com/p/google-gson/source/browse/trunk/gson/src/main/java/com/google/gson/internal/bind/MapTypeAdapterFactory.java

So long as the types of the keys and values can be serialized into JSON strings (and you can create your own serializers/deserializers for these custom objects) you shouldn't have any issues.


In Gson 2.7.2 it's as easy as

Gson gson = new Gson();
String serialized = gson.toJson(map);

Map<String, Object> config = gson.fromJson(reader, Map.class);

ReferenceURL : https://stackoverflow.com/questions/8360836/gson-is-there-an-easier-way-to-serialize-a-map

반응형