【问题标题】:Java GSON - serialize int as strings to json fileJava GSON - 将 int 作为字符串序列化为 json 文件
【发布时间】:2018-01-04 22:09:22
【问题描述】:

我有这个 Java 类:

class Car {
     int mileage;
     int id;
}

当我告诉 gson 对其进行序列化时,它当然会将其序列化为:

{
  "mileage": 123,
  "id": 12345678
}

但如果我想将其序列化为:

{
  "mileage": "123",
  "id": "12345678"
}

假设将我的成员从 int 更改为 String,这不是一种选择,有没有办法告诉 gson 将这些 int 成员序列化为 json 文件的字符串?

【问题讨论】:

标签: java json serialization gson


【解决方案1】:

可能有很多方法可以实现您的愿望。 我将分享两种方法。

FIRST - 使用自定义序列化

第二个 - 使用 JsonAdapter 注解 - 更简单

使用自定义序列化

public static class CarSerializer implements JsonSerializer<Car> {
    public JsonElement serialize(final Car car, final Type type, final JsonSerializationContext context) {
        JsonObject result = new JsonObject();
        result.add("mileage", new JsonPrimitive(Integer.toString(car.getMileage())));
        result.add("id", new JsonPrimitive(Integer.toString(car.getId())));

        return result;
    }
}

要调用它,只需修改您的代码或将以下代码与构造函数一起使用

    Car c = new Car(123, 123456789);
    com.google.gson.Gson gson = new 
    GsonBuilder().registerTypeAdapter(Car.class, new CarSerializer())
            .create();
    System.out.println(gson.toJson(c));

输出应该是

{"mileage":"123","id":"12345678"}

示例 1 的完整代码:

public class SerializationTest {

    public static class Car {
        public int mileage;
        public int id;
    
        public Car(final int mileage, final int id) {
            this.mileage = mileage;
            this.id = id;
        }

        public int getId() {
            return id;
        }

        public void setId(final int id) {
            this.id = id;
        }

        public String getMileage() {
            return mileage;
        }    

        public void setMileage(final String mileage) {
            this.mileage = mileage;
        }

    }    

    public static class CarSerializer implements JsonSerializer<Car> {
        public JsonElement serialize(final Car car, final Type type, final JsonSerializationContext context) {
        JsonObject result = new JsonObject();
        result.add("mileage", new JsonPrimitive(Integer.toString(car.getMileage())));
        result.add("id", new JsonPrimitive(Integer.toString(car.getId())));

        return result;
    }
}

public static void main(final String[] args) {
    Car c = new Car(123, 123456789);
    com.google.gson.Gson gson = new 
    GsonBuilder().registerTypeAdapter(Car.class, new CarSerializer())
            .create();
    System.out.println(gson.toJson(c));
}

}

使用@JsonAdapter 注解

在 Car 类上使用 JsonAdapter 注解

@JsonAdapter(CarAdapter.class)
public class Car {
    public int mileage;
    public int id;
}

创建自定义适配器

public  class CarAdapter extends TypeAdapter<Car> {

    @Override
    public void write(JsonWriter writer, Car car) throws IOException {
        writer.beginObject();

        writer.name("mileage").value(car.getMileage());
        writer.name("id").value(car.getId());  
        writer.endObject();
    }

    @Override
    public Car read(JsonReader in) throws IOException {
        // do something you need
        return null;
    }

}

要序列化,使用这种方法,使用类似这样的东西

Car c = new Car(123, 123456789);
Gson gson = new Gson();    
String result = gson.toJson(c);

在这种情况下打印result应该输出

{"mileage":"123","id":"12345678"}

【讨论】:

    【解决方案2】:

    你可以这样试试:

    new GsonBuilder()
      .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
      .registerTypeAdapter(Integer.class, (JsonSerializer<Integer>)
        (integer, type, jsonSerializationContext) -> new       
          JsonPrimitive(String.valueOf(integer)))
      .excludeFieldsWithoutExposeAnnotation().create();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-19
      • 1970-01-01
      相关资源
      最近更新 更多