将<Map >列出到org.json.JSONObject?
List<Map> list = new ArrayList<Map>(); Map map = new HashMap(); map.put("abc", "123456"); map.put("def", "hmm"); list.add(map); JSONObject json = new JSONObject(list); try { System.err.println(json.toString(2)); } catch (JSONException e) { e.printStackTrace(); }
这段代码出了什么问题?
输出是:
{"empty": false}
public String listmap_to_json_string(List
好吧,试试这个〜这对我有用:D
List
您需要以JSONObjects(Map)的JSONArray(对应于List)结束。
尝试将json变量声明为JSONArray而不是JSONObject(我相信JSONArray构造函数会做正确的事情)。
另外:您可以考虑使用json.org列表中的其他解析器之一:其中大多数允许您的Json“对象”和“数组”本地映射到java.util.Maps和java.util.Lists; 或者在某些情况下也是真正的Java对象。
我的建议是Jackson, http://jackson.codehaus.org/Tutorial ,它允许映射到List / Map / Integer / String / Boolean / null,以及真正的Beans / POJO。 只需给它类型并将数据映射到您,或将Java对象写为Json。 其他像berlios的“json-tools”或google-gson也暴露了类似的function。
您有一个嵌套在列表中的地图。 你试图调用地图而不先迭代列表。 JSON有时感觉像魔术,但实际上并非如此。 我马上就会发布一些代码。
制作地图地图而不是地图列表与JSON更加一致。
JSONObject json = new JSONObject(list); Iterator> it = json.keys(); while (keyed.hasNext()) { String x = (String) it.next(); JSONObject jo2 = new JSONObject(jo.optString(x)); }
这对我有用:
List jsonCategories = new ArrayList (); JSONObject jsonCategory = null; for (ICategory category : categories) { jsonCategory = new JSONObject(); jsonCategory.put("categoryID", category.getCategoryID()); jsonCategory.put("desc", category.getDesc()); jsonCategories.add(jsonCategory); } try { PrintWriter out = response.getWriter(); response.setContentType("text/xml"); response.setHeader("Cache-Control", "no-cache"); _log.info(jsonCategories.toString()); out.write(jsonCategories.toString()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }
如果您使用的是org.json.simple.JSONArray
( https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple/1.1.1 )
List> list = new ArrayList>(); Map map = new HashMap(); map.put("abc", "123456"); map.put("def", "hmm"); list.add(map); JSONArray jsonArray = new JSONArray(); jsonArray.addAll(listOfMaps);
你可以使用两者:
JSONArray
直接作为,
String toJson(Collection> list) { return new JSONArray(list).toString(); }
或者通过使用Java8迭代列表(如@ShadowJohn解决方案):
String toJson(Collection> list) { return new JSONArray( list.stream() .map((map) -> new JSONObject(map)) .collect(Collectors.toList())) .toString(); }
- Spring Data Rest PagingAndSortingRepository AbstractMethodError(RepositoryFactorySupport)
- 没有Spring Boot的Spring Data JPA
- Spring Boot Maven插件 – 没有BOOT-INF目录
- user-mapping.xml文件在guacamole,无效登录中不起作用
- 通过Property禁用Spring Scheduler任务
- 如何在JavaFX中创建具有透明背景的Splash屏幕
- 如何在java中获取数据库的表结构?
- JVM是否会内联对象的实例变量和方法?
- REST API URL中的额外查询参数
- Java Applet网络连接
- 错误:org.springframework.web.HttpMediaTypeNotSupportedException:不支持内容类型’text / plain; charset = UTF-8′