esolve
V2EX  ›  问与答

关于 jackson 的 ObjectMapper

  •  
  •   esolve · May 3, 2017 · 1815 views
    This topic created in 3326 days ago, the information mentioned may be changed or developed.

    下面代码中 变量 s 是一个 List<LinkedHashMap<String, Object>>类型 但是用 ObjectMapper 的时候

    s = mapper.readValue(json, List.class);

    只提供了一维上的类型,即 List.class 而不知道二维的类型,即 LinkedHashMap<String, Object> 而后是用

    LinkedHashMap<String, Object> link = s.get(i);

    得到 link

    可是这种 implicit 的转换是怎么个机制? 是 ObjectMapper 的魔力,悄悄的已经转换好了?

    public static void main(String[] args) {
        ObjectMapper mapper = new ObjectMapper();
        String json = "[{\"uid\":1000,\"uname\":\"xiao liao\",\"upwd\":\"123\",\"number\":12.0,\"isstudent\":true},{\"uid\":200,\"uname\":\"xiao mi\",\"upwd\":null,\"number\":0.0,\"isstudent\":false}]";
        List<LinkedHashMap<String, Object>> s = null;
        try {
            s = mapper.readValue(json, List.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        for (int i = 0; i < s.size(); i++) {
            LinkedHashMap<String, Object> link = s.get(i);
            Set<String> key = link.keySet();
            for (Iterator iterator = key.iterator(); iterator.hasNext(); ) {
                String string = (String) iterator.next();
                System.out.println(string + "==>" + link.get(string));
    
            }
            System.out.println("json:" + i + "" + s.get(i).toString());
        }
    }
    
    2 replies    2017-05-04 11:52:33 +08:00
    tsunli
        1
    tsunli  
       May 3, 2017
    mapper.readValue(json,new TypeReference<List<List<String,String>> (){});
    esolve
        2
    esolve  
    OP
       May 4, 2017
    @tsunli 但是上面用不是你说的这个方法,而是

    readValue(String content, Class<T> valueType)
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1227 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 23:39 · PVG 07:39 · LAX 16:39 · JFK 19:39
    ♥ Do have faith in what you're doing.