Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static class ModelToString extends JsonSerializer<Model> {
- @Override
- public void serialize(Model value,
- JsonGenerator gen,
- SerializerProvider serializers) throws IOException, JsonProcessingException {
- System.out.println("value = " + value);
- gen.writeStartObject();
- gen.writeFieldName("rate1");
- gen.writeNumber(value.rate);
- gen.writeFieldName("count1");
- gen.writeNumber(value.count);
- gen.writeFieldName("content1");
- gen.writeObject(value.content);
- gen.writeEndObject();
- }
- }
- public static class ModelFromString<T> extends JsonDeserializer<Model<T>> {
- @Override
- public Model<T> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
- Model<T> m = new Model<>();
- String t1 = p.nextFieldName();
- p.nextToken();
- m.rate = p.getDoubleValue();
- String t3 = p.nextFieldName();
- p.nextToken();
- m.count = p.getIntValue();
- String t5 = p.nextFieldName();
- p.nextToken();
- m.content = ctxt.readValue(p, (Class<T>) Content.class);
- return m;
- }
- }
- public static class Content {
- @JsonSerialize(using = LocalDateTimeSerializerToString.class)
- @JsonDeserialize(using = LocalDateTimeDeserializerFromString.class)
- public LocalDateTime time;
- public Content() {
- }
- }
- public static class Model<T> {
- public Double rate;
- public Integer count;
- public T content;
- public Model() {
- }
- }
- public static class My {
- @JsonSerialize(using = ModelToString.class)
- @JsonDeserialize(using = ModelFromString.class)
- Model model;
- public Model getModel() {
- return model;
- }
- public void setModel(Model rate) {
- this.model = rate;
- }
- }
- public static void main(String[] args) throws Exception {
- ObjectMapper om = new ObjectMapper();
- om.registerModule(new Jdk8Module());
- om.registerModule(new ParameterNamesModule());
- DeserializationConfig newConfig = om.getDeserializationConfig()
- .with();
- om.setConfig(newConfig);
- My my = new My();
- Model<Content> model = new Model<>();
- model.rate = 2.55;
- model.count = 42;
- Content content = new Content();
- content.time = LocalDateTime.now();
- model.content = content;
- my.setModel(model);
- String str = om.writeValueAsString(my);
- System.out.println("str = " + str);
- My my2 = om.readValue(str, My.class);
- System.out.println("my2 = " + my2);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement