Java Gson:如何更改枚举的输出
我有这个枚举: 在我的请求类中,我有一个字段:Java Gson:如何更改枚举的输出,java,gson,Java,Gson,我有这个枚举: 在我的请求类中,我有一个字段:privateRequestStatus状态 使用Gson将Java对象转换为JSON时,结果如下: "status": "OK" 如何更改GsonBuilder或Enum对象以获得如下输出: "status": { "value" : "OK", "code" : 200 } 您可以使用以下内容: GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapterFa
privateRequestStatus状态
使用Gson将Java对象转换为JSON时,结果如下:
"status": "OK"
如何更改GsonBuilder或Enum对象以获得如下输出:
"status": {
"value" : "OK",
"code" : 200
}
您可以使用以下内容:
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapterFactory(new MyEnumAdapterFactory());
或者更简单地说(正如杰西·威尔逊所指出的):
及
公共类MyEnumAdapterFactory实现TypeAdapterFactory{
@凌驾
公共类型适配器创建(最终Gson Gson,最终TypeToken类型){
类除了Polet的答案之外,如果您需要一个通用枚举序列化程序,您可以通过反射实现它:
public class EnumAdapterFactory implements TypeAdapterFactory
{
@Override
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type)
{
Class<? super T> rawType = type.getRawType();
if (rawType.isEnum())
{
return new EnumTypeAdapter<T>();
}
return null;
}
public class EnumTypeAdapter<T> extends TypeAdapter<T>
{
@Override
public void write(JsonWriter out, T value) throws IOException
{
if (value == null || !value.getClass().isEnum())
{
out.nullValue();
return;
}
try
{
out.beginObject();
out.name("value");
out.value(value.toString());
Arrays.stream(Introspector.getBeanInfo(value.getClass()).getPropertyDescriptors())
.filter(pd -> pd.getReadMethod() != null && !"class".equals(pd.getName()) && !"declaringClass".equals(pd.getName()))
.forEach(pd -> {
try
{
out.name(pd.getName());
out.value(String.valueOf(pd.getReadMethod().invoke(value)));
} catch (IllegalAccessException | InvocationTargetException | IOException e)
{
e.printStackTrace();
}
});
out.endObject();
} catch (IntrospectionException e)
{
e.printStackTrace();
}
}
public T read(JsonReader in) throws IOException
{
// Properly deserialize the input (if you use deserialization)
return null;
}
}
}
公共类EnumAdapterFactory实现TypeAdapterFactory
{
@凌驾
公共类型适配器创建(最终Gson Gson,最终TypeToken类型)
{
Class@DennisMadsen在这里,我把它作为代码的一个内部类。你是否错过了它,或者我不理解你的问题?谢谢。你能给我一个例子,我如何在write方法中更改JsonWriter吗?@DennisMadsen我添加了一些示例代码,我认为这正是你想要的。仅供参考,这太棒了。你可以节省时间通过如下方式注册工厂类:registerTypeAdapter(RequestStatus,new MyEnumTypeAdapter())@Shark查看com.google.gson.internal.bind.ObjectTypeAdapter
的代码,看看对象是如何反序列化的。这与在这里实现的行为完全相同。这很好,但请注意,它序列化了getter,而不是枚举字段。
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(RequestStatus.class, new MyEnumTypeAdapter());
public class MyEnumAdapterFactory implements TypeAdapterFactory {
@Override
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {
Class<? super T> rawType = type.getRawType();
if (rawType == RequestStatus.class) {
return new MyEnumTypeAdapter<T>();
}
return null;
}
public class MyEnumTypeAdapter<T> extends TypeAdapter<T> {
public void write(JsonWriter out, T value) throws IOException {
if (value == null) {
out.nullValue();
return;
}
RequestStatus status = (RequestStatus) value;
// Here write what you want to the JsonWriter.
out.beginObject();
out.name("value");
out.value(status.name());
out.name("code");
out.value(status.getCode());
out.endObject();
}
public T read(JsonReader in) throws IOException {
// Properly deserialize the input (if you use deserialization)
return null;
}
}
}
public class EnumAdapterFactory implements TypeAdapterFactory
{
@Override
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type)
{
Class<? super T> rawType = type.getRawType();
if (rawType.isEnum())
{
return new EnumTypeAdapter<T>();
}
return null;
}
public class EnumTypeAdapter<T> extends TypeAdapter<T>
{
@Override
public void write(JsonWriter out, T value) throws IOException
{
if (value == null || !value.getClass().isEnum())
{
out.nullValue();
return;
}
try
{
out.beginObject();
out.name("value");
out.value(value.toString());
Arrays.stream(Introspector.getBeanInfo(value.getClass()).getPropertyDescriptors())
.filter(pd -> pd.getReadMethod() != null && !"class".equals(pd.getName()) && !"declaringClass".equals(pd.getName()))
.forEach(pd -> {
try
{
out.name(pd.getName());
out.value(String.valueOf(pd.getReadMethod().invoke(value)));
} catch (IllegalAccessException | InvocationTargetException | IOException e)
{
e.printStackTrace();
}
});
out.endObject();
} catch (IntrospectionException e)
{
e.printStackTrace();
}
}
public T read(JsonReader in) throws IOException
{
// Properly deserialize the input (if you use deserialization)
return null;
}
}
}
@Test
public void testEnumGsonSerialization()
{
List<ReportTypes> testEnums = Arrays.asList(YourEnum.VALUE1, YourEnum.VALUE2);
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapterFactory(new EnumAdapterFactory());
Gson gson = builder.create();
System.out.println(gson.toJson(reportTypes));
}