我有一个配置文件来指定要从JSON文档中提取的字段,然后我要写入CSV文件。
目前,我正在遍历JSON文档,并将指定的键和值分配给HashMap<String,Object> ,然后将这些键添加到ArrayList<HashMap<String,Object>> 。 看起来这个地图是在JSON文档中读取信息时填充的。
如何将我的地图按照配置文件中指定的字段顺序排序? 我在网上搜索,但只发现如何按字母顺序或数字排序的例子,这不是我想要的。
配置: "useFields":["id","created","subject","status","priority"]
当前输出: ["created:16-Feb-2017, id:1234, priority:low, status:Foo, subject:Bar"]
期望输出: ["id:1234, created:16-Feb-2017, subject:Bar, status:Foo, priority:low"]
I have a configuration file to specify fields to extract from a JSON document, which I then want to write to a CSV file.
At the moment, I am iterating through the JSON document and assigning the specified keys and values to a HashMap<String,Object>, and then adding those to an ArrayList<HashMap<String,Object>>. It seems that the map is populated as the information is read from the JSON document.
How can I sort my maps to be in the order of the fields specified in the configuration file? I've searched online but only found examples on how to sort alphabetically or numerically which is not what I want.
Configuration: "useFields":["id","created","subject","status","priority"]
Current output: ["created:16-Feb-2017, id:1234, priority:low, status:Foo, subject:Bar"]
Desired output: ["id:1234, created:16-Feb-2017, subject:Bar, status:Foo, priority:low"]
最满意答案
标准Java类LinkedHashMap按照它们添加的顺序对映射条目进行排序。 事实证明,使用Groovy“map literal”语法时创建的实际对象实际上就是LinkedHashMap 。 因此,获得所需的效果与创建空地图文字以及按照所需顺序添加现有地图中的条目一样简单:
final useFields = ["id","created","subject","status","priority"] def input = [created:"16-Feb-2017", id:1234, priority:"low", status:"Foo", subject:"Bar"] println input def output = [:] useFields.each { output[it] = input[it] } // or this one-liner: // def output = useFields.inject([:]) { out, key -> out[key] = input[key]; out } println outputThe standard Java class LinkedHashMap sorts map entries in the order they were added. And, as it turns out, the actual object created when you use the Groovy "map literal" syntax is, in fact, LinkedHashMap. So, getting the effect you want is as simple as creating an empty map literal and adding the entries from the existing map in the order desired:
final useFields = ["id","created","subject","status","priority"] def input = [created:"16-Feb-2017", id:1234, priority:"low", status:"Foo", subject:"Bar"] println input def output = [:] useFields.each { output[it] = input[it] } // or this one-liner: // def output = useFields.inject([:]) { out, key -> out[key] = input[key]; out } println output更多推荐
发布评论