jaxrs could not find my custom (de)serializers for joda.money type

前端 未结 1 643
栀梦
栀梦 2021-01-23 22:27

I have written my custom (de)serializer for joda.money.Moneytype. I register them with Object Mapper. But when I deploy my war file, it says could not find serializ

1条回答
  •  伪装坚强ぢ
    2021-01-23 23:00

    I see that you create ObjectMapper in JsonProvider constructor but never use it. You probably should use setMapper(mapper); on JsonProvider at the very end of the constructor.

    But i don't think this will solve your problem. I think the problem is that jaxrs understands only simple data types and if you want to use custom class you have to implement some sort of String marshalling for String based @*Param

    From your stacktrace i see that you use jboss, so maybe this can help? https://docs.jboss.org/resteasy/docs/3.0.12.Final/userguide/html/StringConverter.html

    What if you have a class where valueOf() or this string constructor doesn't exist or is inappropriate for an HTTP request? JAX-RS 2.0 has the javax.ws.rs.ext.ParamConverterProvider to help in this situation. See javadoc for more details.

    https://docs.oracle.com/javaee/7/api/javax/ws/rs/ext/ParamConverterProvider.html

    Something like this should probably work:

    @Provider
    public class MoneyConverterProvider  implements ParamConverterProvider {
    
        private final MoneyConverter converter = new MoneyConverter();
    
        @Override
        public  ParamConverter getConverter(Class rawType, Type genericType, Annotation[] annotations) {
            if (!rawType.equals(Money.class)) return null;
            return (ParamConverter) converter; 
        }
    
        public class MoneyConverter implements ParamConverter {
    
            public Money fromString(String value) {
                if (value == null ||value.isEmpty()) return null; // change this for production
                return Money.of(CurrencyUnit.EUR, Double.parseDouble(value));
            }
    
            public String toString(Money value) {
                if (value == null) return "";
                return value.getAmount().toString(); // change this for production
            }
    
        }
    }
    

    0 讨论(0)
提交回复
热议问题