0

I am fetching a JSON object from an API with includes:

"palette": ["#019701","#FE82B8","#FAFF04","#017FFF","#FD8141"],

I have pojo like:

public class PanelInfo {
//    ...
    private Color[] colorPalette;
//    ...
}

To deserialize I tried adding:

class ColorJsonDeserializer extends JsonDeserializer<Color> {

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

and other variations of extracting from p.getValueAsString().

No go. Everything I try returns:

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of java.awt.Color (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('#221875')

It seems I am not working with the JsonParser correctly. Any ideas?

Update: Thanks to https://stackoverflow.com/users/11713777/dariosicily This is working code:

public class PanelInfo {
...
@JsonDeserialize(contentUsing = ColorJsonDeserializer.class)
public Color[] palette;
...
}

and deserializer class:

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import java.awt.Color; 
import java.io.IOException;


 public  class ColorJsonDeserializer extends JsonDeserializer<Color> {

    @Override
    public Color deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        return new Color(Integer.parseUnsignedInt(p.getValueAsString().substring(1), 16));
    }

}

Note the substring to get rid of the leading #

Scaddenp
  • 67
  • 11
  • 1
    Have you registered the deserializer with your object mapper? – Michał Krzywański Nov 22 '21 at 21:28
  • 1
    Does this answer your question? [Unable to deserialize java.awt.color using jackson deserializer](https://stackoverflow.com/questions/42070673/unable-to-deserialize-java-awt-color-using-jackson-deserializer) – Nowhere Man Nov 22 '21 at 22:44
  • michael - yes, I did. Alex, what I used to help me write the deserializer but the issue is an array of color. – Scaddenp Nov 23 '21 at 20:05

1 Answers1

1

You can annotate your palette field with the JsonDeserialize annotation and the contentUsing deserializer class because palette is a Color array and not a single value:

public class PanelInfo {

    @JsonDeserialize(contentUsing = ColorJsonDeserializer.class)
    private Color[] palette;
}
dariosicily
  • 4,239
  • 2
  • 11
  • 17