Gson does not parse class variable

I use Gson and I have an object that one of its fields is a class

class A { … private Class aClass; … } 

When I parse a Json instance using the default Gson object, aClass is empty.

Any idea why?

+4
source share
2 answers

You need a custom type adapter. Here is an example:

 package com.sopovs.moradanen; import java.lang.reflect.Type; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; public class GsonClassTest { public static void main(String[] args) { Gson gson = new GsonBuilder() .registerTypeAdapter(Class.class, new ClassTypeAdapter()) .setPrettyPrinting() .create(); String json = gson.toJson(new Foo()); System.out.println(json); Foo fromJson = gson.fromJson(json, Foo.class); System.out.println(fromJson.boo.getName()); } public static class ClassTypeAdapter implements JsonSerializer<Class<?>>, JsonDeserializer<Class<?>> { @Override public JsonElement serialize(Class<?> src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(src.getName()); } @Override public Class<?> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { try { return Class.forName(json.getAsString()); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } } public static class Foo { Class<?> boo = String.class; } } 

The output of this code is:

 { "boo": "java.lang.String" } java.lang.String 
+5
source

When I parse a Json instance using the default Gson object, aClass is empty.

Any idea why?

In a comment in issue 340 , the Gson project manager explains:

Type serialization is actually a security issue, so we don’t want to support it by default. The malicious .json file may cause your application to load classes that otherwise would not; depending on the path of your class, loading certain classes may make your application.

But it's pretty simple to write a type adapter to support this in your own application.

Of course, since serialization is not the same as deserialization, I don’t understand how this explanation of disabled serialization is, unless the notion mentioned does not mean to “balance” the default behavior of serialization with deserialization.

+3
source

Source: https://habr.com/ru/post/1381085/


All Articles