Deserialize JSON into a generic map, forcing all JSON floats into Decimal or String, in Jackson

本小妞迷上赌 提交于 2019-12-24 04:55:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!