簡體   English   中英

Gson 自定義序列化具有自定義注釋的字段

[英]Gson custom serialization for fields with custom annotation

class Demo {
  private String name;
  private int total;

   ...
}

當我用 gson 序列化演示的 object 時,在正常情況下我會得到這樣的結果:

{"name": "hello world", "total": 100}

現在,我有一個注釋@Xyz ,它可以添加到任何 class 的任何屬性中。 (我可以應用此注釋的屬性可以是任何東西,但現在如果它只是String類型應該沒問題)

class Demo {
  @Xyz
  private String name;

  private int total;

  ...
}

當我對 class 屬性進行注釋時,序列化數據應采用以下格式:

{"name": {"value": "hello world", "xyzEnabled": true}, "total": 100}

請注意,無論 class 的類型如何,此注釋都可以應用於任何(字符串)字段。 如果我能以某種方式在自定義序列化程序序列serialize方法上獲得該特定字段的聲明注釋,那對我有用。

請建議如何實現這一目標。

我認為您打算將注釋 JsonAdapter與您的自定義行為一起使用

這是一個示例 class Xyz,它擴展了 JsonSerializer、JsonDeserializer

import com.google.gson.*;

import java.lang.reflect.Type;

public class Xyz implements JsonSerializer<String>, JsonDeserializer<String> {

  @Override
  public JsonElement serialize(String element, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject object = new JsonObject();
    object.addProperty("value", element);
    object.addProperty("xyzEnabled", true);
    return object;
  }

  @Override
  public String deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    return json.getAsString();
  }
}

這是一個示例使用

import com.google.gson.annotations.JsonAdapter;

public class Demo {
  @JsonAdapter(Xyz.class)
  public String name;
  public int total;
}

我已經寫了更多的測試也許他們會幫助你更多地解決這個問題

import com.google.gson.Gson;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class Custom {
  @Test
  public void serializeTest() {
    //given
    Demo demo = new Demo();
    demo.total = 100;
    demo.name = "hello world";
    //when
    String json = new Gson().toJson(demo);
    //then
    assertEquals("{\"name\":{\"value\":\"hello world\",\"xyzEnabled\":true},\"total\":100}", json);
  }

  @Test
  public void deserializeTest() {
    //given
    String json = "{  \"name\": \"hello world\",  \"total\": 100}";
    //when
    Demo demo = new Gson().fromJson(json, Demo.class);
    //then
    assertEquals("hello world", demo.name);
    assertEquals(100, demo.total);
  }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM