Java Arraylist Data extraction

前端 未结 3 719
感情败类
感情败类 2021-01-25 06:47

How would you extract the data as follows:

I want to extract from this arraylist:

[{itemname=Original, number=12}, {itemname=BBQ, number=23}, {itemname=C         


        
相关标签:
3条回答
  • 2021-01-25 07:30

    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!

    0 讨论(0)
  • 2021-01-25 07:45

    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
    
    0 讨论(0)
  • 2021-01-25 07:45

    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"}]}
    
    0 讨论(0)
提交回复
热议问题