[英]Gson - Serialize any null value to empty string
我正在使用gson序列化某些對象。 我有一個要求,任何空字段都應被視為空字符串,而與變量是字符串,雙精度或pojo無關。
我試圖為對象創建一個自定義序列化器,並只為空值對象返回一個新的JsonPrimitive(“”),但是問題是如何在不使用“ instanceof”或“ getClass”的情況下處理非空值對象處理每種單一類型。
任何有關如何執行此操作的想法都值得贊賞。
可以使用模型Object
的自定義TypeAdaptor
完成此操作。
您可以使用反射來遍歷object字段,並且只要字段為null
,只要您跨越null字段,就將json表示中的值設置為空字符串。
正如@Sotirios Delimanolis所述, 這絕對是很難維護的,並且應該承擔一些風險, 如果相應的引用不是String ,該如何來回處理呢?
public class MyEntity
{
private int id;
private String name;
private Long socialNumber;
private MyInnerEntity innerEntity;
public MyEntity(int id, String name, Long socialNumber, MyInnerEntity innerEntity)
{
this.id = id;
this.name = name;
this.socialNumber = socialNumber;
this.innerEntity = innerEntity;
}
public int getId()
{
return id;
}
public String getName()
{
return name;
}
public Long getSocialNumber()
{
return socialNumber;
}
public MyInnerEntity getInnerEntity()
{
return innerEntity;
}
public static class MyInnerEntity {
@Override
public String toString()
{
return "whateverValue";
}
}
}
TypeAdapter
實現,該實現將任何null
值設置為並為空“” String
: public class GenericAdapter extends TypeAdapter<Object>
{
@Override
public void write(JsonWriter jsonWriter, Object o) throws IOException
{
jsonWriter.beginObject();
for (Field field : o.getClass().getDeclaredFields())
{
Object fieldValue = runGetter(field, o);
jsonWriter.name(field.getName());
if (fieldValue == null)
{
jsonWriter.value("");
}
else {
jsonWriter.value(fieldValue.toString());
}
}
jsonWriter.endObject();
}
@Override
public Object read(JsonReader jsonReader) throws IOException
{
/* Don't forget to add implementation here to have your Object back alive :) */
return null;
}
/**
* A generic field accessor runner.
* Run the right getter on the field to get its value.
* @param field
* @param o {@code Object}
* @return
*/
public static Object runGetter(Field field, Object o)
{
// MZ: Find the correct method
for (Method method : o.getClass().getMethods())
{
if ((method.getName().startsWith("get")) && (method.getName().length() == (field.getName().length() + 3)))
{
if (method.getName().toLowerCase().endsWith(field.getName().toLowerCase()))
{
try
{
return method.invoke(o);
}
catch (IllegalAccessException e)
{ }
catch (InvocationTargetException e)
{ }
}
}
}
return null;
}
}
Gson
的簡單直接的main
方法: public class Test
{
public static void main(String[] args)
{
Gson gson = new GsonBuilder().registerTypeAdapter(MyEntity.class, new GenericAdapter()).create();
Object entity = new MyEntity(16, "entity", (long)123, new MyEntity.MyInnerEntity());
String json = gson.toJson(entity);
System.out.println(json);
Object entity2 = new MyEntity(0, null, null, null);
json = gson.toJson(entity2);
System.out.println(json);
}
}
這將導致以下輸出:
{"id":"16","name":"entity","socialNumber":"123","innerEntity":"whateverValue"}
{"id":"0","name":"","socialNumber":"","innerEntity":""}
請注意,無論對象的類型是什么,其值在編組的json字符串中均設置為“”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.