[英]How to convert a JSON map into a custom Java list, using Gson?
[英]how to convert List of map to json in java
//请找到下面的代码。我无法将map转换为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;
}
好像您创建了HashMap<String, String> branch = new HashMap<>();
一旦在while循环之外,但您需要为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中没有任何内容(甚至[]
没有),则意味着文件解析有问题。 编辑: 评论后情况并非如此
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.