簡體   English   中英

Java Gson 到 Json 轉換

[英]Java Gson to Json Conversion

我有一個 class 具有以下屬性,

public AnalyticsEventProperty(String eventID, String key, Object value, EventPropertyValueType valueType) {
        this.eventID = eventID;
        this.key = key;
        this.value = value;
        this.type = valueType();
}

這個 object 被創建並傳遞給一個事件屬性數組,當我執行 Json 轉換時,我得到下面的 output:

{"eventID":"afc970ef-80cf-4d6e-86e6-e8f3a56f26f5","name":"app_start","propertyArrayList":[{"eventID":"afc970ef-80cf-4d6e-86e6-e8f3a56f26f5","key":"session_id","value":"69200430-95a0-4e14-9a36-67942917573d"}

我正在使用'鍵和'值',我知道為什么,但是我如何使用鍵和值作為鍵和值,即“session_id”:“69200430-95a0-4e14-9a36-67942917573d”,請記住這些鍵和值可能具有不同的屬性名稱,具體取決於構造函數中傳遞的內容。

當我創建字符串時,我只是在調用

String text_to_send = new Gson().toJson(events);

其中 events 是 ArrayList。

您可以通過編寫自定義TypeAdapterFactory來解決此問題,它為您的 class(即基於反射的適配器)獲取默認適配器,並使用它以JsonObject的形式創建內存中的 JSON 表示。 然后可以修改該JsonObject以具有您期望的結構; 之后必須將其寫入JsonWriter

class RewritingEventPropertyAdapterFactory implements TypeAdapterFactory {
  public static final RewritingEventPropertyAdapterFactory INSTANCE = new RewritingEventPropertyAdapterFactory();

  private RewritingEventPropertyAdapterFactory() {}

  @Override
  public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    // Only consider AnalyticsEventProperty or subtypes
    if (!AnalyticsEventProperty.class.isAssignableFrom(type.getRawType())) {
      return null;
    }

    TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
    TypeAdapter<JsonObject> jsonObjectAdapter = gson.getAdapter(JsonObject.class);

    return new TypeAdapter<T>() {
      @Override
      public T read(JsonReader in) throws IOException {
        throw new UnsupportedOperationException("Deserialization is not supported");
      }

      @Override
      public void write(JsonWriter out, T value) throws IOException {
        if (value == null) {
          out.nullValue();
          return;
        }

        JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject();

        // Remove "key" and "value"
        String eventKey = jsonObject.remove("key").getAsString();
        JsonElement eventValue = jsonObject.remove("value");

        // Add back an entry in the form of `"key": "value"`
        jsonObject.add(eventKey, eventValue);

        // Write the transformed JsonObject
        jsonObjectAdapter.write(out, jsonObject);
      }
    };
  }
}

然后,您必須使用GsonBuilder 注冊工廠

另一種方法是通過將屬性直接寫入JsonWriter手動執行 class 的完整序列化。 這很可能會更高效,但也更容易出錯。

暫無
暫無

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

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