Map<String, HashSet<String>> to JSON, & Pretty Print

风格不统一 提交于 2019-11-29 15:53:05

You could manually set the key names, something like:

ArrayNode array = mapper.createArrayNode();
for (Entry entry: yourMap.entries()) {
  ObjectNode node = mapper.createObjectNode()
      .put("name", entry.key())
      .putPOJO("ids", entry.value());
  array.add(node);
}
mapper.writeValue(file, array);

Alternatively, you could create a class for your data

class MyEntity {
  String name;
  Set<String> ids; // use names that you want in the JSON result
  // getters, setters if necessary
}

Transform your data map into a list of MyEntity, then use Jackson ObjectMapper to create JSON like mapper.writeValue(file, listOfMyEntities), the output would be like

[
  {
    "name": "some name here",
    "ids": ["id1", "id2", ...]  
  }
  // more elements here
]

how about this:

        String name_list_file = "/home/matthias/Workbench/SUTD/nytimes_corpus/NYTimesCorpus/2005/01/02/test/people_test.txt";

        String single_name;

        try (   
                // read in the original file, list of names, w/e
                InputStream stream_for_name_list_file = new FileInputStream( name_list_file );
                InputStreamReader stream_reader = new InputStreamReader( stream_for_name_list_file , Charset.forName("UTF-8"));
                BufferedReader line_reader = new BufferedReader( stream_reader );
            ) 
        {
            while (( single_name = line_reader.readLine() ) != null) 
            {
                //replace this by a URL encoder
                //String associated_alias = single_name.replace(' ', '+');
                String associated_alias = URLEncoder.encode( single_name , "UTF-8");

                String platonic_key = single_name;
                System.out.println("now processing: " + platonic_key);

                Wikidata_Q_Reader.getQ( platonic_key, associated_alias );
            }
        }

        //print the struc
        Wikidata_Q_Reader.print_data();


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