Json到Java的映射 [英] Json to Java Mapping

查看:69
本文介绍了Json到Java的映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将下面的Json数据映射到List<Map<String, String>>类型的Java对象.

I want to map below Json data to java object of List<Map<String, String>> type.

Json示例:

{ 
  {
    a:b,
    c:d
  },
  {
    e:f,
    g:h,
    i:j
  },
  { 
   h:k
  }
}

此处a:b表示键值对.因此,a:bc:d将映射到列表的第一个映射,依此类推. 一种方法是通过构建JSON树并访问每个节点并将该对​​存储到地图中.

Here a:b represents key-value pair. So a:b and c:d will be mapped to first map of the list and so on. one way to do this is by building JSON tree and access each node and store the pair into the map.

是否有更好的方法(更清洁的方法)?

Is there a better way to do this (cleaner approach)?

推荐答案

以下是使用杰克逊库读取List<Map<String, String>>的代码,并将示例数据作为输入:

Here is the code to read a List<Map<String, String>> using the Jackson library, with your example data as input:

public class JsonTest {
public static void main(String[] args) throws Exception {
    final String json
        = "[\n"
        + "    {\n"
        + "        \"a\":\"b\",\n"
        + "        \"c\":\"d\"\n"
        + "    },\n"
        + "    {\n"
        + "        \"e\":\"f\",\n"
        + "        \"g\":\"h\",\n"
        + "        \"i\":\"j\"\n"
        + "    },\n"
        + "    {\n"
        + "        \"h\":\"k\"\n"
        + "    }\n"
        + "]"; // [{a:b,c:d},{e:f,g:h,i:j},{h:k}]   
    ObjectMapper mapper = new ObjectMapper();
    TypeFactory factory = TypeFactory.defaultInstance();
    List<Map<String, String>> list = mapper.readValue(json,factory
        .constructCollectionType(List.class, factory
                .constructMapType(Map.class, String.class, String.class)));
    System.out.println(list.toString());
}
}

注意:我必须将最外面的花括号从{}修复为[],这是正确的JSON列表语法.

Note: I had to fix your outermost braces from {} to [], which is the correct JSON list syntax.

这篇关于Json到Java的映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆