您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何在JSP / Java中创建多维HashMap或Hashtable并将其转换为JSON对象?

如何在JSP / Java中创建多维HashMap或Hashtable并将其转换为JSON对象?

在JSON中,{}可以映射为Java Map,并且[]可以映射为Java List

因此,要实现以下JSON格式,

{
  "results": [ {
    "address_components": [ {
      "long_name": "1600",
      "short_name": "1600"
    }, {
      "long_name": "Amphitheatre Pkwy",
      "short_name": "Amphitheatre Pkwy"
    }, {
      "long_name": "Mountain View",
      "short_name": "Mountain View"
    }, {
      "long_name": "California",
      "short_name": "CA"
    }, {
      "long_name": "United States",
      "short_name": "US"
    }, {
      "long_name": "94043",
      "short_name": "94043"
    } ]
  } ]
}

你需要( 深呼吸Map<String, List<Map<String, List<Map<String, String>>>>>

List<Map<String, String>> addressComponents = new ArrayList<Map<String, String>>();
Map<String, String> addressComponent1 = new HashMap<String, String>();
addressComponent1.put("long_name", "1600");
addressComponent1.put("short_name", "1600");
addressComponents.add(addressComponent1);
Map<String, String> addressComponent2 = new HashMap<String, String>();
addressComponent2.put("long_name", "Amphitheatre Pkwy");
addressComponent2.put("short_name", "Amphitheatre Pkwy");
addressComponents.add(addressComponent2);
// ...

List<Map<String, List<Map<String, String>>>> results = new ArrayList<Map<String, List<Map<String, String>>>>();
Map<String, List<Map<String, String>>> result1 = new HashMap<String, List<Map<String,String>>>();
result1.put("address_components", addressComponents);
results.add(result1);
// ...

Map<String, List<Map<String, List<Map<String, String>>>>> god = new HashMap<String, List<Map<String,List<Map<String,String>>>>>();
god.put("results", results);
String json = new Gson().toJson(god);
System.out.println(json); // There!

更好的是只使用完全有价值的Javabeans代替Map<String, String>

java 2022/1/1 18:17:28 有536人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶