Jackson框架提供的JsonGenerator ObjectMapper以及JSONObject 、
1、jackson 框架:这个框架提供了JsonGenerator ,ObjectMapper两个类通过这两个类提供的方法可以将java 对象转化为json 对象,json 数组格式,也可以将json对象、数组格式转化为java对象。 2、json-lib框架也可以进行json格式和java 对象之间的相互转化,json-lib提供的类主要有:JSONObject,JSONArray…. 3、展现使用两种框架进行相互转化: 一、json-lib: list.add(u2); // 创建JSONObject 对象 JSONObject jobg = new JSONObject(); // 创建JSONObject 对象 JSONArray arr = new JSONArray(); // 将对象转化为json对象的格式 JSONObject str = jobg.fromObject(u); // 将list集合转化为json数组的格式 JSONArray str1 = arr.fromObject(list); System.out.print(str); System.out.print("n"); System.out.print(str1); } } /* 运行结果 */ {“age”:1,”name”:”name1”,”phone”:”123”} 二、jackson框架提供的两个类 JsonGenerator ObjectMapper package com.jackson.test; try { jg = obj.getJsonFactory().createJsonGenerator(System.out,JsonEncoding.UTF8); System.out.println("jsonGenerator"); // writeObject可以转换java对象,eg:JavaBean/Map/List/Array等 jg.writeObject(u); System.out.println(); jg.writeObject(list); System.out.println(); System.out.println("ObjectMapper"); // writeValue具有和writeObject相同的功能 obj.writeValue(System.out,list); } catch (Exception e) { e.printStackTrace(); } } } / * 运行结果 */ jsonGenerator {“name”:”name1”,”age”:1,”sex”:”man”} [{“name”:”name1”,”sex”:”man”},{“name”:”name2”,”age”:2,”sex”:”man”}] ObjectMapper [{“name”:”name1”,”sex”:”man”}] (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |