Jackson的JSON处理-ObjectMapper

Jackson可以轻松的将Java对象转换成json对象和xml文档,同样也可以将json、xml转换成Java对象
准备工作
1、 下载依赖库jar包
Jackson的jar all    jackson-all-1.7.6.jar
因为下面的程序是用junit测试用例运行的,所以还得添加junit的jar包
如果你需要转换xml,那么还需要stax2-api.jar
2、 测试类基本代码如下
public class Jackson {  

    public  static JsonGenerator jsonGenerator = null;
    private static ObjectMapper mapper = new ObjectMapper();
    public static void main(String[] args) {
        Student student = new Student();
        student.setIsstudent(true);
        student.setUid(1000);
        student.setUname("xiao liao");
        student.setUpwd("123");
        student.setNumber(12);  

        Map<String, Student> stuMap = new HashMap<String, Student>();
        stuMap.put("1", student);
        stuMap.put("2", student);  

        List<Object> stuList = new ArrayList<Object>();
        List<Student> stuList1 = new ArrayList<Student>();
        stuList1.add(student);
        student=  new  Student();
        student.setIsstudent(false);
        student.setUid(200);
        student.setUname("xiao mi");
        stuList1.add(student);  

        stuList.add(student);
        stuList.add("xiao xin");
        stuList.add("xiao er");
        stuList.add(stuMap);  

        //readJson2List();
        try {
            //readJson2Array();
            //writeArray2Json(array);
            //writeJson2List();
            //writeEntity2Json(student);
            writeJson2Entity();
            //writeMap2Json(stuMap);
            //writeList2Json(stuList1);
        } catch (IOException e) {e.printStackTrace();}
    } 

     public static void writeEntity2Json(Object object) throws IOException {
        mapper.writeValue( new File("D:\\testjson1\\lib\\aa.txt"),object );
        mapper.writeValue( System.out,object );
     } 

     public static void writeArray2Json(Object object) throws IOException {
         // writeValue具有和writeObject相同的功能
         mapper.writeValue( new File("D:\\testjson1\\lib\\aa.txt"),object );
         mapper.writeValue(System.out,object );
     }  

     public static void writeMap2Json(Object object) throws IOException {
         System.out.println("使用ObjectMapper-----------");
         // writeValue具有和writeObject相同的功能
         System.out.println("==>"+mapper.writeValueAsString(object));
         mapper.writeValue( new File("D:\\testjson1\\lib\\aamap.txt"),object );
         mapper.writeValue( System.out , object );
     }  

     public static void writeList2Json(Object object) throws IOException {
         System.out.println("==>"+mapper.writeValueAsString(object));
         mapper.writeValue( new File("D:\\testjson1\\lib\\aamap.txt"),object );
         mapper.writeValue( System.out , object );
     }  

     public static void writeJson2Entity() throws IOException {
         System.out.println("json串转换成entity-------------");
//       File file = new File("D:\\testjson1\\lib\\aa.txt");
//       FileInputStream inputStream = new FileInputStream(file);
//       Student student = mapper.readValue(inputStream,Student.class);
//       System.out.println(student.toString());
         //mapper.defaultPrettyPrintingWriter().writeValueAsString(value);  

         String json = "{\"uid\":1000,\"uname\":\"xiao liao\",\"upwd\":\"123\",\"number\":12.0,\"isstudent\":true}";
         Student student1 = mapper.readValue(json,Student.class);
         System.out.println("json2:"+student1.toString());
     }  

     public static void writeJson2List() throws IOException {
         System.out.println("json串转换成entity-------------");
         File file = new File("D:\\testjson1\\lib\\aa.txt");
         FileInputStream inputStream = new FileInputStream(file);
         Student student = mapper.readValue(inputStream,Student.class);
         System.out.println(student.toString());  

         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= mapper.readValue(json,List.class);
         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());
        }
     }
     //JSON转换为List对象
      public static void readJson2List() {
       String json = "[{\"uid\":1,\"uname\":\"www\",\"number\":234,\"upwd\":\"456\"},"
         + "{\"uid\":5,\"uname\":\"tom\",\"number\":3.44,\"upwd\":\"123\"}]";
       try {
        List<LinkedHashMap<String, Object>> list = mapper.readValue(
          json, List.class);
        System.out.println(list.size());
        for (int i = 0; i < list.size(); i++) {
         Map<String, Object> map = list.get(i);
         Set<String> set = map.keySet();
         for (Iterator<String> it = set.iterator(); it.hasNext();) {
          String key = it.next();
          System.out.println(key + ":" + map.get(key));
         }
        }
       } catch (JsonParseException e) {e.printStackTrace();
       } catch (JsonMappingException e) {e.printStackTrace();
       } catch (IOException e) {e.printStackTrace();}
      }
      //JSON转换为List对象
      public static void readJson2Array() {
          String json = "[{\"uid\":1,\"uname\":\"www\",\"number\":234,\"upwd\":\"456\"},"
              + "{\"uid\":5,\"uname\":\"tom\",\"number\":3.44,\"upwd\":\"123\"}]";
          try {
              Student[] students = mapper.readValue(json, Student[].class);
              for (Student student : students) {
                System.out.println(">"+student.toString());
            }
          } catch (JsonParseException e) {e.printStackTrace();
          } catch (JsonMappingException e) {e.printStackTrace();
          } catch (IOException e) {e.printStackTrace();}
      }
}
打印结果 :
串转换成entity-------------
json2:uid=1000,name=xiao liao,upwd=123,number=12.0,isStudent=true

writeMap2Json -----------
{"2":{"uid":1000,"uname":"xiao liao","upwd":"123","number":12.0,"isstudent":true},"1":{"uid":1000,"uname":"xiao liao","upwd":"123","number":12.0,"isstudent":true}}

readJson2Array------------------
>uid=1,name=www,upwd=456,number=234.0,isStudent=false
>uid=5,name=tom,upwd=123,number=3.44,isStudent=false
writeMap2Json -----------
{"2":{"uid":1000,"uname":"xiao liao","upwd":"123","number":12.0,"isstudent":true},"1":{"uid":1000,"uname":"xiao liao","upwd":"123","number":12.0,"isstudent":true}}
public class Student {
      private int uid;
      private String uname;
      private String upwd;
      private double number;
      private boolean isstudent;
     getset方法
}  
时间: 2024-11-08 19:59:07

Jackson的JSON处理-ObjectMapper的相关文章

Java下利用Jackson进行JSON解析和序列化

ava下常见的Json类库有Gson.JSON-lib和Jackson等,Jackson相对来说比较高效,在项目中主要使用Jackson进行JSON和Java对象转换,下面给出一些Jackson的JSON操作方法. 一.准备工作 Jackson有1.x系列和2.x系列,2.x系列有3个jar包需要下载:jackson-core-2.2.3.jar(核心jar包)jackson-annotations-2.2.3.jar(该包提供Json注解支持)jackson-databind-2.2.3.ja

使用 jackson 解析 json 示例

首先需要下载3个包,下载地址在Github FasterXML,这三个核心模块分别是: Streaming ("jackson-core") defines low-level streaming API, and includes JSON-specific implementations Annotations ("jackson-annotations") contains standard Jackson annotations Databind (&quo

Java下利用Jackson进行JSON解析和序列化1

Java下常见的Json类库有Gson.JSON-lib和Jackson等,Jackson相对来说比较高效,在项目中主要使用Jackson进行JSON和Java对象转换,下面给出一些Jackson的JSON操作方法. 一.准备工作 首先去官网下载Jackson工具包,下载地址http://wiki.fasterxml.com/JacksonDownload.Jackson有1.x系列和2.x系列,截止目前2.x系列的最新版本是2.2.3,2.x系列有3个jar包需要下载: jackson-cor

Jackson Gson Json.simple part 2

这篇blog介绍 Jackson 的特点和使用方法 Jackson支持三种使用方法 流API(streaming api Incremental parsing/generation) JsonParse reads, JsonGenerator writes 高效 和part 1 json的用法类似,不好用 树形模型 ObjectMapper用来建树,和JsonNode配合使用 数据绑定 Json与POJO相互转换 简单数据转换 简单对象是指java中的map, list等等 全数据转换 自定

Java下用Jackson进行JSON序列化和反序列化(转)

Java下常见的Json类库有Gson.JSON-lib和Jackson等,Jackson相对来说比较高效,在项目中主要使用Jackson进行JSON和Java对象转换,下面给出一些Jackson的JSON操作方法. 一.准备工作 首先去官网下载Jackson工具包,下载地址http://wiki.fasterxml.com/JacksonDownload.Jackson有1.x系列和2.x系列,截止目前2.x系列的最新版本是2.9.0,2.x系列有3个jar包需要下载: jackson-cor

SpringMVC使用jackson转json格式

如果没有使用json转换器,在ajax请求的返回方法声明@ResponseBody时,会出现以下错误 "NetworkError: 406 Not Acceptable - http://uc.com:8081/login/check" /login/check请求映射的方法如下 @RequestMapping("/login/check") @ResponseBody public Map<String, String> loginCheck(Http

spring-data-jpa——如果使用了one-to-many,many-to-one的注解,在Jackson进行json字符串化时出现错误的解决方案

参考资料: http://blog.csdn.net/remote_roamer/article/details/51330843 http://blog.csdn.net/xiaodaiye/article/details/51118870 在spring-data-jpa中,使用了one-to-many和many-to-one注解,在进行json字符串化时出现错误. 经查阅资料找到以下解决方法: 通过在主表的pojo中增加@JsonManagedReference来注解关联字段: @OneT

Java中使用Jackson进行JSON解析和序列化

Java中使用Jackson进行JSON解析和序列化 1.添加依赖,在Maven的pom.xml文件中添加以下依赖 <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.5.3</version> </dependency> 2.封装JSON解

4.使用Jackson将Json数据转换成实体数据

Jar下载地址:http://jackson.codehaus.org/ 注意:类中的属性名称一定要和Json数据的属性名称一致(大小写敏感),类之间的嵌套关系也应该和Json数据的嵌套关系一致. 4.使用Jackson将Json数据转换成实体数据,布布扣,bubuko.com