How I parse Color java class to JSON with Jackson?

Viewed 820

I am trying to deserialise the Color class from JSON with Jackson but it throws exception:

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "colorSpace" (class java.awt.Color), not marked as ignorable.

What i'm doing wrong? This is my code:

File act = new File(new File().getAbsolutePath());

ObjectMapper om = new ObjectMapper();
File f = new File(act, "123.JSON");

om.writeValue(f, new person());
person per = om.readValue(f, person.class);
System.out.println(per);

This is my person class:

public class person implements Serializable {
    //it include getters, setters and builder

   String nombe = "Pepe";
   String CI = "12345678978";
   Color c = Color.red;
}
1 Answers

java.awt.Color class is not a regular POJO or Enum. You need to implement custom serialiser and deserialiser if you want to store it in JSON format. Color class can be represented by its RGB representation and you can store it as a number:

class ColorJsonSerializer extends JsonSerializer<Color> {

    @Override
    public void serialize(Color value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (value == null) {
            gen.writeNull();
            return;
        }
        gen.writeNumber(value.getRGB());
    }
}

class ColorJsonDeserializer extends JsonDeserializer<Color> {

    @Override
    public Color deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        return new Color(p.getValueAsInt());
    }
}

Simple usage:

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;

import java.awt.*;
import java.io.IOException;

public class JsonPathApp {

    public static void main(String[] args) throws Exception {
        SimpleModule awtModule = new SimpleModule("AWT Module");
        awtModule.addSerializer(Color.class, new ColorJsonSerializer());
        awtModule.addDeserializer(Color.class, new ColorJsonDeserializer());

        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(awtModule);

        String json = mapper.writeValueAsString(new Person());
        System.out.println(json);

        System.out.println(mapper.readValue(json, Person.class));
    }
}

Above code prints:

{"nombe":"Pepe","c":-65536,"ci":"12345678978"}
Person{nombe='Pepe', CI='12345678978', c=java.awt.Color[r=255,g=0,b=0]}

Take a look on similar question where Color is stored as JSON object:

Related