zoukankan      html  css  js  c++  java
  • 关于在controller中json数据与对象,map,list的相互转换 jackson

    关于在controller中json数据与对象,map,list的相互转换

    步骤:
    1.导入jackson相关jar包

    • jackson-annotations.jar
    • jackson-core.jar
    • jackson-databind.jar


    com.fasterxml.jackson.core
    jackson-core
    2.7.3


    com.fasterxml.jackson.core
    jackson-databind
    2.7.3


    com.fasterxml.jackson.core
    jackson-annotations
    2.7.3

    2.创建jackson的核心对象:ObjectMapper
    ObjectMapper mapper = new ObjectMapper();

    3.调用mapper的相关方法

    对象转json

    User user = new User("Tom","沈阳");
    String json = mapper.writeValueAsString(user);
    System.out.print(json); //输出:{"name":"Tom","city","沈阳"}

    Map<String,String>转json

    HashMap<String,String> map = new HashMap<String,String>();
    map.put("name","Kris");
    map.put("city","沈阳");
    String json = mapper.writeValueAsString(map);
    System.out.print(json); //输出:{"city":"沈阳","name":"Kris"} (HashMap是无序的)


    Map<String,Object>转json

    Map<String,User> map = new HashMap<String,User>();
    map1.put("01",new User("Tom","沈阳"));
    map1.put("02",new User("Kris","上海"));
    String json = mapper.writeValueAsString(map1);
    System.out.println(json);
    输出:
    {
    "01":{"name":"Tom","city":"沈阳"},
    "02":{"name":"Kris","city":"上海"}
    }

    ArrayList转为json

    ArrayList al = new ArrayList();
    al.add("Tom");
    al.add("沈阳");
    String json = mapper.writeValueAsString(al);
    System.out.print(json); //输出:["TOM","SHENYANG"]

    ArrayList转为json

    ArrayList al = new ArrayList();
    al.add(new User("Tom","沈阳"));
    al.add(new User("Kris","上海"));
    String json = mapper.writeValueAsString(al);
    System.out.print(json);
    输出:
    [
    {"name":"Tom","city":"沈阳"},
    {"name":"Kris","city":"上海"}
    ]

    json转对象
    String json = "{"name":"Tom","city":"沈阳"}";
    User user = mapper.readValue(json, User.class);
    System.out.println(user);

    json转map<String,String>

    HashMap<String,String> map = mapper.readValue(json, HashMap.class);
    System.out.println(map);

    json转map<String,Object>

    Map<String,User> map= mapper.readValue(json, HashMap.class);
    System.out.println(map);

    json转list

    ArrayList list= mapper.readValue(json, ArrayList.class);
    System.out.println(list);

    json转list

    List list= mapper.readValue(json, ArrayList.class);
    System.out.println(list);

  • 相关阅读:
    u-boot 2011.09 调用kernel 的流程
    Delphi repeat Until 运用
    clientdataset的使用
    类型TTreeView.items.add 与 TTreeView.items.addchild有何区别?(10分)
    delphi中nil、null、UnAssigned区别
    操作TreeView(咏南工作室)
    delphi7 treeview + 数据库 实现动态节点维护
    Delphi Try Except 实例
    Delphi 中自定义异常及异常处理的一般方法
    Delphi中的异常处理(10种异常来源、处理、精确处理)
  • 原文地址:https://www.cnblogs.com/torchstar/p/12560559.html
Copyright © 2011-2022 走看看