序列化为日期时间、对象

我有这种格式的地图,

HashMap<String, Object> map = {"RequestsServed":{"2019-06-28T00:00:00Z":0.0},"PullRequests":{"2019-06-28T00:00:00Z":0.0}}

我的意图是做map.get("RequestsServed")并获得一张地图, {"2019-06-28T00:00:00Z":0.0}而不管其中的键值对的数量。

我尝试使用,

HashMap<DateTime, Object> result = new ObjectMapper().readValue(SerializationUtils.toJson(map.get("RequestsServed").toString()), HashMap.class);

并失败了。请帮忙。谢谢


皈依舞
浏览 145回答 2
2回答

侃侃尔雅

我问这个问题太蠢了。。。map.get("RequestsServed") 会给我一个 LinkedTreeMap。我只需要将它解析为我选择的 HashMap 即可。将 map.get("RequestsServed") 序列化为 json 并将结果值解析为 HashMap 将轻松为我提供所需的结果。谢谢大家的宝贵时间。

叮当猫咪

我写了一个虚拟类用于测试目的:public class TempObject {&nbsp; &nbsp; private String date;&nbsp; &nbsp; private Double value;&nbsp; &nbsp; public TempObject(String date, Double value) {&nbsp; &nbsp; &nbsp; &nbsp; this.date = date;&nbsp; &nbsp; &nbsp; &nbsp; this.value = value;&nbsp; &nbsp; }&nbsp; &nbsp; public String getDate() {&nbsp; &nbsp; &nbsp; &nbsp; return date;&nbsp; &nbsp; }&nbsp; &nbsp; public Double getValue() {&nbsp; &nbsp; &nbsp; &nbsp; return value;&nbsp; &nbsp; }}这是您的解决方案:// Initializing the Map (I'm using LinkedHashMap here for a reason)Map<String, Object> map = new LinkedHashMap<>();map.put("RequestsServed", new TempObject("2019-06-28T00:00:00Z", 0.0));map.put("PullRequests", new TempObject("2019-06-28T00:00:00Z", 0.1));// Using Collectors.toMap() with mergeFunction (to handle duplicate keys)Map<String, Object> result = map.values().stream().map(object -> (TempObject) object).collect(Collectors.toMap(TempObject::getDate, TempObject::getValue, (existingValue, newValue) -> newValue));System.out.println(result); // printing the value of result map: {2019-06-28T00:00:00Z=0.1}您还可以将此 String 值解析为LocalDateTime.
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java