如何在java中将map的List转换为json

时间:2017-09-17 15:05:46

标签: java json collections jersey gson

//请找到下面的代码。我无法将地图转换为json对象

@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("readCsv")
public @ResponseBody String readCsvservice(@Context ServletContext servletContext) throws Exception {

    String csvFile = System.getProperty("user.dir") + "/resources/branch_profitability.csv";
    String line = "";
    String cvsSplitBy = ",";

    HashMap<String, String> branch = new HashMap<>();

    List<Map> branchList = new ArrayList<>();

    try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
        br.readLine();
        while ((line = br.readLine()) != null) {

            // use comma as separator
            String[] country = line.split(cvsSplitBy);
            branch.put("Zone", country[0]);
            branch.put("State", country[1]);
            branch.put("City", country[2]);
            branch.put("Location", country[3]);
            branch.put("brach", country[4]);
            branch.put("Employee", country[5]);
            branch.put("EOP", country[6]);
            branchList.add(branch);
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
    ObjectMapper objectMapper = new ObjectMapper();

    // try1
    String jsonMap = objectMapper.writeValueAsString(branchList);

    // try2
    String json = new Gson().toJson(branchList);

    return json;

}

1 个答案:

答案 0 :(得分:0)

看起来你在while循环之外创建HashMap<String, String> branch = new HashMap<>();,但你需要为csv中的每一行创建新的HashMap。

// HashMap<String, String> branch = new HashMap<>(); <= remove this line

List<Map> branchList = new ArrayList<>();

try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
    br.readLine();
    while ((line = br.readLine()) != null) {

        HashMap<String, String> branch = new HashMap<>(); //<= Add this line

        // fill new map...

        branchList.add(branch);
    }

} catch (IOException e) {
    e.printStackTrace();
}

但是你的代码实际上应该生成csv中最后一条记录的json乘以行数,所以如果你在json中得不到任何东西(甚至不是[]),那就意味着什么是你的文件解析错了。编辑:不是comment

之后的情况