Map> to JSON, & Pretty Print

后端 未结 2 1168
花落未央
花落未央 2020-12-21 16:13

I\'m trying to make my dataset correspond to this example:

var family = [{
    \"name\" : \"Jason\",
    \"age\" : \"24\",
    \"gender\" : \"male\"
},
{
            


        
相关标签:
2条回答
  • 2020-12-21 16:23

    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();
    
    
        }
    
    0 讨论(0)
  • 2020-12-21 16:34

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