English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

كيفية استخدام Gson لإنشاء JsonAdapter مخصص في Java؟

 @JsonAdapte التعليقات يمكن استخدامها في المستوى الحالي أو المستوى الكلاسي لتعريف GSON.TypeAdapterالصف يمكن استخدامه لتحويل أوبجكتات Java إلى JSON. بشكل افتراضي، مكتبة Gson تحول كلاس التطبيق إلى JSON باستخدام مروبات النوع المدمجة، ولكن يمكننا تغيير ذلك بتقديم مروبات نوع مخصصة.

النحو

@Retention(value=RUNTIME)
@Target(value={TYPE,FIELD})
public @interface JsonAdapter

مثال

import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
public class JsonAdapterTest {
   public static void main(String[] args) {
      Gson gson = new Gson();
      System.out.println(gson.toJson(new Customer()));
   }
}
//Customer category
class Customer {
   @JsonAdapter(CustomJsonAdapter.class)
   Integer customerId = 101;
}
//CustomJsonAdapter class
class CustomJsonAdapter extends TypeAdapter<Integer> {
   @Override
   public Integer read(JsonReader jreader) throws IOException {
      return null;
   }
   @Override
   public void write(JsonWriter jwriter, Integer customerId) throws IOException {
      jwriter.beginObject();
      jwriter.name("customerId");
      jwriter.value(String.valueOf(customerId));
      jwriter.endObject();
   }
}

نتيجة الإخراج

{"customerId":{"customerId":"101"}}
مثل ما تفضله