简体   繁体   English

序列化为日期时间、对象

[英]Serialize into Datetime, Object

I have map in this format,我有这种格式的地图,

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

My intension is to do map.get("RequestsServed") and get a map of {"2019-06-28T00:00:00Z":0.0} irrespective of number of key, value pair in it.我的意图是做map.get("RequestsServed")并获得{"2019-06-28T00:00:00Z":0.0}的地图,而不管其中的键值对的数量。

I tried using,我尝试使用,

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

and failed.并失败了。 please help.请帮忙。 Thanks谢谢

I was so dumb asking this question...问这个问题我太傻了...

map.get("RequestsServed") is gonna give me a LinkedTreeMap. map.get("RequestsServed") 会给我一个 LinkedTreeMap。 I just have to parse it into a HashMap of my choice.我只需要将其解析为我选择的 HashMap。

serialising map.get("RequestsServed") to a json and parse the resultant value to HashMap will give me the required result easily.将 map.get("RequestsServed") 序列化为 json 并将结果值解析为 HashMap 将很容易给我所需的结果。

Thank you all for your time.谢谢大家的时间。

I have written a dummy class for testing purpose:我写了一个虚拟类用于测试目的:

public class TempObject {
    private String date;
    private Double value;

    public TempObject(String date, Double value) {
        this.date = date;
        this.value = value;
    }

    public String getDate() {
        return date;
    }

    public Double getValue() {
        return value;
    }
}

And here is your solution:这是您的解决方案:

// 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}

You can also parse this String value to LocalDateTime .您还可以将此 String 值解析为LocalDateTime

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM