Wiki
Clone wikijose4j / Jackson and JWK
The code snippets below show how a custom Jackson Json serializer and deserializer can be used to properly serialize/deserialize JsonWebKey objects that are part of a larger object tree.
public class JWKJsonDeserializer extends StdDeserializer<JsonWebKey> { public JWKJsonDeserializer() { super(JsonWebKey.class); } @Override public JsonWebKey deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { try { Map<String,Object> params = jsonParser.readValueAs(new TypeReference<Map<String, Object>>(){}); return JsonWebKey.Factory.newJwk(params); } catch (JoseException e) { throw new JsonParseException(jsonParser, "Unable to parse Json Web Key"); } } }
public class JWKJsonSerializer extends StdSerializer<JsonWebKey> { public JWKJsonSerializer() { super(JsonWebKey.class); } @Override public void serialize(JsonWebKey jsonWebKey, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonGenerationException { jsonGenerator.writeObject(jsonWebKey.toParams(OutputControlLevel.INCLUDE_SYMMETRIC)); } }
// Add the serializer and deserializer to the field containing the key. public static class TestObject { @JsonSerialize(using = JWKJsonSerializer.class) @JsonDeserialize(using = JWKJsonDeserializer.class) public JsonWebKey key; }
Updated