Java GSON - serialize int as strings to json file

烈酒焚心 提交于 2021-02-08 06:43:28

问题


I have this Java class:

class Car {
     int mileage;
     int id;
}

When I tell gson to serialize it, it of course serializes it to:

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

But what if I want to serialize it to:

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

Assuming changing my members from int to String, is not an option, is there a way to tell gson to serialize those int members as strings to the json file?


回答1:


There are likely many ways to achieve what you desire. I will share two ways.

FIRST - Using Custom Serialization

SECOND - Using JsonAdapter Annotation - More Simple

Using a custom serialization

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;
    }
}

To call this, simply adapt your code or use the following code with a constructor

    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));

The output should be

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

Full Code for Example 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));
}

}

Using a @JsonAdapter annotation

Use the JsonAdapter Annotation on the Car class

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

Create the Custom Adapter

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;
    }

}

To serialize, using this method, use something like this

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

Printing result in this case should output

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



回答2:


You may try it this way:

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


来源:https://stackoverflow.com/questions/48104306/java-gson-serialize-int-as-strings-to-json-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!