CustomLastUpdatedUserSerializer extends JsonSerializer<User> { @Override public void serialize( User user, JsonGenerator jsonGenerator, SerializerProvider serializerProvider ) throws IOException { ToXmlGenerator xmlGenerator = null; if ( jsonGenerator instanceof ToXmlGenerator ) { xmlGenerator = (ToXmlGenerator) jsonGenerator; } jsonGenerator.writeStartObject(); if ( xmlGenerator != null ) { xmlGenerator.setNextIsAttribute( true ); xmlGenerator.setNextName( null ); } jsonGenerator.writeStringField( "id", user.getUid() ); jsonGenerator.writeStringField( "name", user.getDisplayName() ); jsonGenerator.writeEndObject(); }  @Override void serialize( User user, JsonGenerator jsonGenerator, SerializerProvider serializerProvider );  }
@Test public void serializeXml() throws Exception { Writer jsonWriter = new StringWriter(); ToXmlGenerator jsonGenerator = new XmlFactory().createGenerator( jsonWriter ); SerializerProvider serializerProvider = new ObjectMapper().getSerializerProvider(); jsonGenerator.setNextName( new QName( "urn:test", "lastUpdatedBy" ) ); new CustomLastUpdatedUserSerializer().serialize( user, jsonGenerator, serializerProvider ); jsonGenerator.flush(); assertEquals( "<wstxns1:lastUpdatedBy xmlns:wstxns1=\"urn:test\" id=\"jshfdkd323\" name=\"Peter Brown\"/>", jsonWriter.toString() ); }
@Test public void serializeJson() throws Exception { Writer jsonWriter = new StringWriter(); JsonGenerator jsonGenerator = new JsonFactory().createGenerator( jsonWriter ); SerializerProvider serializerProvider = new ObjectMapper().getSerializerProvider(); new CustomLastUpdatedUserSerializer().serialize( user, jsonGenerator, serializerProvider ); jsonGenerator.flush(); assertEquals( "{\"id\":\"jshfdkd323\",\"name\":\"Peter Brown\"}", jsonWriter.toString() ); }