Java Arraylist Data extraction

强颜欢笑 提交于 2019-12-20 04:23:08

问题


How would you extract the data as follows:

I want to extract from this arraylist:

[{itemname=Original, number=12}, {itemname=BBQ, number=23}, {itemname=CatchUp, number=23}]

This array:

{"Original":12,"BBQ":23,"CatchUp":23}

Thanks in advance! Here's the code used to generate the hashmap:

ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
for (int i = 0; i<7;i++) {
 HashMap<String,String> map = new HashMap<String,String>();
  map.put("itemname",chips[i]);
  map.put("number",chipentry[i]);
  list.add(map);
 }

回答1:


It looks like you want to convert it to Json, using google gson http://code.google.com/p/google-gson/ its very easy

"Provide simple toJson() and fromJson() methods to convert Java objects to JSON and vice-versa"

Here is what I mean :

Gson gson = new Gson();
gson.toJson(map); //where map is your map object



回答2:


Thanks for the tip - I have changed to the following code:

  ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
  Gson gson = new Gson();
  for (int i = 0; i<7;i++) {
     HashMap<String,String> map = new HashMap<String,String>();
     map.put("itemname",chips[i]);
     map.put("number",chipentry[i]);
     list.add(map);
     System.out.println(gson.toJson(map));
  }

And the result is http://imgur.com/E7uds.png

I imported com.google.gson.Gson, is there something else I'm missing? Please excuse my newbness and thanks for the help!




回答3:


To extract the data as you expected, you can use Jackson JSON processor. It allows you to read and write JSON easily. You can follow their tutorial here.

Fist you have to download the relevant jar files(2 files) provided by them.

So the following code snippet should solve your problem, and the result is written to the jsonResult.json file.

    String[] chips = {"Original", "BBQ", "CatchUp"};
    String[] chipentry = {"12", "23", "23"};

    List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
    for (int i = 0; i < 3; i++) {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("itemname", chips[i]);
        map.put("number", chipentry[i]);
        list.add(map);
    }

    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> untyped = new HashMap<String, Object>();

    untyped.put("result", list);
    mapper.writeValue(new File("jsonResult.json"), untyped);

And following is the output of the file,

{"result":[{"itemname":"Original","number":"12"},{"itemname":"BBQ","number":"23"},{"itemname":"CatchUp","number":"23"}]}


来源:https://stackoverflow.com/questions/5592575/java-arraylist-data-extraction

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