问题
I am using Jackson in the jsonrpc4j to access a remote service. In my Java application there are no defined classes for the return values, so deserialization produces generic LinkedHashMaps. So I cannot put any annotations anywhere. jsonrpc4j can take in a Jackson ObjectMapper object. The remote service responds with structured json objects, some fields of which are very big decimal numbers, and Jackson treats them as Doubles. An example object can look like this
{"s1":"zxcvb","f1":20.00234,"a1":[{"f2":3883.99400943},{"f3":0.00093944432}]}
I would like it instead interpreting all the numbers as either strings or Decimals with configurable precision and parsing them correctly according to those types. Is it possible to do this using a modified ObjectMapper object? If not that, what would be the easiest way to achieve this?
回答1:
I think I found it: On my first search I missed that Jackson serialization had both SerializationFeatures and DeserializationFeatures, and they are a little different. According to http://fasterxml.github.io/jackson-databind/javadoc/2.0.0/com/fasterxml/jackson/databind/DeserializationFeature.html there is a feature called USE_BIG_DECIMAL_FOR_FLOATS
Feature that determines whether JSON floating point numbers are to be deserialized into BigDecimals if only generic type description (either Object or Number, or within untyped Map or Collection context) is available.
So in my case it was basically
ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
JsonRpcHttpClient rpcHttpClient = new JsonRpcHttpClient(
mapper,
new URL("the url"),
new HashMap<String, String>());
来源:https://stackoverflow.com/questions/16309840/deserialize-json-into-a-generic-map-forcing-all-json-floats-into-decimal-or-str