有没有办法将不同的字符串集合合并到一个 JSON“字符串”中? 我想要一个如下所示的 JSON 字符串:
{"vendor":[Sun, HP, IBM],"product":[bla, bla, bla],"availability":[high, mid, low],"capacity":[bla, bla, bla], ...}
这是我的 Java 代码的一部分:
Collection<String> vendor = bh.getAllVendors();
Collection<String> product = bh.getProductsForVendor(vendor);
Collection<String> availability = bh.getAllAvailabilities();
Collection<String> capacity = bh.getCapacityForVendor(vendor);
Collection<String> signaling = bh.getSignalingForVendor(vendor);
Collection<String> backup = bh.getBackupForVendor(vendor);
Gson gson = new Gson();
如有任何帮助,我们将不胜感激。
最佳答案
如果将它们添加到 map 中会最简单:
Gson gson = new Gson();
Map<String, Collection<String>> map = new HashMap<>();
map.put("vendor", vendor);
map.put("product", product);
//etc
System.out.println(gson.toJson(map));
生产
{"product":["bla","bla","bla"],"vendor":["Sun","IBM","HP"]}
关于java - 使用 GSON 将多个 Collection<String> 合并为一个 JSON String,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10244547/