Java的Jackson库中有一复杂液位对象对象集合的几种简单

博客分类:
在解析JSON方面,无疑JACKSON是做的最好的,下面从几个方面简单复习下。
1 JAVA 对象转为JSON
&
import java.io.F
import java.io.IOE
import org.codehaus.jackson.JsonGenerationE
import org.codehaus.jackson.map.JsonMappingE
import org.codehaus.jackson.map.ObjectM
public class JacksonExample {
public static void main(String[] args) {
User user = new User();
ObjectMapper mapper = new ObjectMapper();
// convert user object to json string, and save to a file
mapper.writeValue(new File("c:\\user.json"), user);
// display to console
System.out.println(mapper.writeValueAsString(user));
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
输出为:
{"age":29,"messages":["msg 1","msg 2","msg 3"],"name":"mkyong"}
2 JSON反序列化为JAVA对象
&&
import java.io.F
import java.io.IOE
import org.codehaus.jackson.JsonGenerationE
import org.codehaus.jackson.map.JsonMappingE
import org.codehaus.jackson.map.ObjectM
public class JacksonExample {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
// read from file, convert it to user class
User user = mapper.readValue(new File("c:\\user.json"), User.class);
// display to console
System.out.println(user);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
输出:User [age=29, name=mkyong, messages=[msg 1, msg 2, msg 3]]
3 在上面的例子中,如果要输出的JSON好看点,还是有办法的,就是使用
defaultPrettyPrintingWriter()方法,例子为:
User user = new User();
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.defaultPrettyPrintingWriter().writeValueAsString(user));
则输出整齐:
{
& "age" : 29,
& "messages" : [ "msg 1", "msg 2", "msg 3" ],
& "name" : "mkyong"
}
&
浏览 20990
浏览: 5974619 次
来自: 广州
有些扩展名为null
非常感谢!!!!!!!!!
https://zhuban.me竹板共享 - 高效便捷的文档 ...
kris_zhang 写道如果有多个@Primary 会怎么样 ...
(window.slotbydup=window.slotbydup || []).push({
id: '4773203',
container: s,
size: '200,200',
display: 'inlay-fix'如何用JACKSON将JSON转换成一个复杂的自定义类型对象
<a data-traceid="question_detail_above_text_l&&
public class CustomExport {
private String queryF
private String[] selectedC
private String[] selectedA
private List&CustomColumn& customColumnL
public class CustomColumn {
/*自定义列ID*/
private String columnId;
/*自定义列名*/
private String columnN
/*筛选方式*/
private String filterT
/*筛选字段*/
private List&String& filterF
/*关键字,筛选方式为关键字时用到*/
/*表达式,筛选方式为表达式时用到*/
CustomExport customExport = objectMapper.readValue( , javaType);
如何将获取到的json直接转化成类CustomExport的对象 不知如何构建这种javaType
直接用CustomExport.class即可,要保证CustomExport和CustomColum有默认的构造方法。
javaType = CustomExport.class项目文件列表
版权所有 (C) 2017 5lulu.com. All Right Reserved. 为中华文化之崛起而奋斗!Java的Jackson库中复杂对象集合的几种简单转换
转载 &更新时间:日 11:56:00 & 作者:renjiaqi_500Server
本文主要介绍了Java的Jackson库中复杂对象集合的几种简单转换。具有很好的参考价值,下面跟着小编一起来看下吧
话不多说,请看代码:
import java.io.BufferedR
import java.io.ByteArrayInputS
import java.io.IOE
import java.io.InputStreamR
import java.util.L
import com.fasterxml.jackson.core.JsonParseE
import com.fasterxml.jackson.databind.JavaT
import com.fasterxml.jackson.databind.JsonMappingE
import com.fasterxml.jackson.databind.ObjectM
* jackson 复杂 对象集合 的几种简单转换
* @author lenovo
* @param &T&
public class Main&T&
static ObjectMapper mapper = new ObjectMapper();
public static void main(String[] args) throws JsonParseException,
JsonMappingException, IOException
String josn = "{\"UserID\":1,\"LoginName\":\"唐工\",\"Truename\":\"超级\",\"Nickname\":null,\"LoginPwd\":\"E10ADC3949BA59ABBE56E057F20F883E\",\"QQ\":\"\",\"Phone\":\"\",\"Email\":null,\"Remark\":\"\",\"Account_Non_Locked\":0,\"Telelephone\":null,\"IsDelete\":0}";
User u = mapper.readValue(josn, User.class);
// User u=new Main&User&().jsonStreamConverObject(josn, User.class);
System.out.println("转对象:" + u);
String josn2 = "[{\"UserID\":1,\"LoginName\":\"唐工\",\"Truename\":\"超级\",\"Nickname\":null,\"LoginPwd\":\"E10ADC3949BA59ABBE56E057F20F883E\",\"QQ\":\"\",\"Phone\":\"\",\"Email\":null,\"Remark\":\"\",\"Account_Non_Locked\":0,\"Telelephone\":null,\"IsDelete\":0}]";
JavaType javaType = mapper.getTypeFactory().constructParametricType(
List.class, User.class);
List&User& me = mapper.readValue(josn2, javaType);
System.out.println("转集合me:" + me);
// 对象里有 集合 转换
String josn3 = "{\"UserID\":1,\"LoginName\":\"唐工\",\"Truename\":\"超级\",\"Nickname\":null,\"LoginPwd\":\"E10ADC3949BA59ABBE56E057F20F883E\",\"QQ\":\"\",\"Phone\":\"\",\"Email\":null,\"Remark\":\"\",\"Account_Non_Locked\":0,\"Telelephone\":null,\"IsDelete\":0,\"RoleList\":[{\"Roleid\":0,\"Name\":\"超级管理员\",\"Show_Name\":\"超级管理员\",\"Remark\":null,\"Type\":1}]}";
User u3 = mapper.readValue(josn3, User.class); // 简单方式
// User u3=new Main&User&().jsonConverObject(josn3, User.class); 流方式
System.out.println("转对象里有集合u3:" + u3);
// 集合 对象 集合 转换
String josn4 = "[{\"UserID\":1,\"LoginName\":\"唐工\",\"Truename\":\"超级\",\"Nickname\":null,\"LoginPwd\":\"E10ADC3949BA59ABBE56E057F20F883E\",\"QQ\":\"\",\"Phone\":\"\",\"Email\":null,\"Remark\":\"\",\"Account_Non_Locked\":0,\"Telelephone\":null,\"IsDelete\":0,\"RoleList\":[{\"Roleid\":0,\"Name\":\"超级管理员\",\"Show_Name\":\"超级管理员\",\"Remark\":null,\"Type\":1}]},{\"UserID\":2,\"LoginName\":\"唐工\",\"Truename\":\"超级\",\"Nickname\":null,\"LoginPwd\":\"E10ADC3949BA59ABBE56E057F20F883E\",\"QQ\":\"\",\"Phone\":\"\",\"Email\":null,\"Remark\":\"\",\"Account_Non_Locked\":0,\"Telelephone\":null,\"IsDelete\":0,\"RoleList\":[{\"Roleid\":0,\"Name\":\"超级管理员\",\"Show_Name\":\"超级管理员\",\"Remark\":null,\"Type\":1}]}]";
JavaType javaType4 = mapper.getTypeFactory().constructParametricType(
List.class, User.class);
List&User& list = mapper.readValue(josn4, javaType4);
System.out.println("集合里是对象 对象里有集合转换:" + list);
* @param josn
* @param clz
public T jsonStreamConverObject(String josn, Class&T& clz)
// ObjectMapper jacksonMapper = new ObjectMapper();
InputStreamReader in = new InputStreamReader(new ByteArrayInputStream(
josn.getBytes()));
BufferedReader streamReader = new BufferedReader(in);
StringBuilder buff = new StringBuilder();
String inputS
while ((inputStr = streamReader.readLine()) != null)
buff.append(inputStr);
// ObjectMapper mapper = new ObjectMapper();
t = mapper.readValue(buff.toString(), clz);
} catch (IOException e)
e.printStackTrace();
* @param josn
* @param clz
public T jsonConverObject(String josn, Class&T& clz)
t = mapper.readValue(josn, clz);
} catch (JsonParseException e)
e.printStackTrace();
} catch (JsonMappingException e)
e.printStackTrace();
} catch (IOException e)
e.printStackTrace();
* @param josn
* @param clz
public List&T& jsonConverList(String josn, Class&T& clz)
List&T& me =
// jacksonMapper
// .disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
// jacksonMapper.enableDefaultTyping();
// jacksonMapper.setVisibility(JsonMethod.FIELD,JsonAutoDetect.Visibility.ANY);
// jacksonMapper.configure(SerializationConfig.Feature.INDENT_OUTPUT,
// false);//格式化
// jacksonMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
// jacksonMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS,
// false);
JavaType javaType = mapper.getTypeFactory()
.constructParametricType(List.class, clz);// clz.selGenType().getClass()
me = mapper.readValue(josn, javaType);
} catch (JsonParseException e)
e.printStackTrace();
} catch (JsonMappingException e)
e.printStackTrace();
} catch (IOException e)
e.printStackTrace();
* 转对象:User [UserID=1, LoginName=唐工, Truename=超级, Nickname=null, LoginPwd=E10ADC3949BA59ABBE56E057F20F883E, QQ=, Phone=, Email=null, Remark=, Account_Non_Locked=0, Telelephone=null, Indate=null, IsDelete=0, RoleList=null]
* 转集合me:[User [UserID=1, LoginName=唐工, Truename=超级, Nickname=null, LoginPwd=E10ADC3949BA59ABBE56E057F20F883E, QQ=, Phone=, Email=null, Remark=, Account_Non_Locked=0, Telelephone=null, Indate=null, IsDelete=0, RoleList=null]]
* 转对象里有集合u3:User [UserID=1, LoginName=唐工, Truename=超级, Nickname=null, LoginPwd=E10ADC3949BA59ABBE56E057F20F883E, QQ=, Phone=, Email=null, Remark=, Account_Non_Locked=0, Telelephone=null, Indate=null, IsDelete=0, RoleList=[Role [Roleid=0, Name=超级管理员, Show_Name=超级管理员, Remark=null, Type=1]]]
* 集合里是对象 对象里有集合转换:[User [UserID=1, LoginName=唐工, Truename=超级, Nickname=null, LoginPwd=E10ADC3949BA59ABBE56E057F20F883E, QQ=, Phone=, Email=null, Remark=, Account_Non_Locked=0, Telelephone=null, Indate=null, IsDelete=0, RoleList=[Role [Roleid=0, Name=超级管理员, Show_Name=超级管理员, Remark=null, Type=1]]], User [UserID=2, LoginName=唐工, Truename=超级, Nickname=null, LoginPwd=E10ADC3949BA59ABBE56E057F20F883E, QQ=, Phone=, Email=null, Remark=, Account_Non_Locked=0, Telelephone=null, Indate=null, IsDelete=0, RoleList=[Role [Roleid=0, Name=超级管理员, Show_Name=超级管理员, Remark=null, Type=1]]]]
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持脚本之家!
您可能感兴趣的文章:
大家感兴趣的内容
12345678910
最近更新的内容
常用在线小工具举例讲解Java的Jackson库中ObjectMapper类的使用
转载 &更新时间:日 12:03:45 & 投稿:goldensun
这篇文章主要介绍了举例讲解Java的Jackson库中ObjectMapper类的使用,Jackson库通常被用来实现Java的对象和JSON之间的转换功能,需要的朋友可以参考下
ObjectMapper类是Jackson库的主要类。它提供一些功能将转换成Java对象匹配JSON结构,反之亦然。它使用JsonParser和JsonGenerator的实例实现JSON实际的读/写。
以下是org.codehaus.jackson.map.ObjectMapper类的声明:
public class ObjectMapper
extends ObjectCodec
implements Versioned
static class ObjectMapper.DefaultTypeResolverBuilder//定制TypeResolverBuilder,提供所谓的“默认输入”使用类型解析构建器(见enableDefaultTyping()了解详细信息)。
static class ObjectMapper.DefaultTyping//使用enableDefaultTyping()枚举指定什么样的类型(类)默认输入应该使用。
构造函数 & 描述
ObjectMapper()//默认的构造函数,这将构建默认JsonFactory必要时使用StdSerializerProvider作为其SerializerProvider,并BeanSerializerFactory作为其SerializerFactory。
ObjectMapper(JsonFactory jf)//构造使用指定的JsonFactory构建必要的JsonParsers和/或JsonGenerators映射。
ObjectMapper(JsonFactory jf, SerializerProvider sp, DeserializerProvider dp)
ObjectMapper(JsonFactory jf, SerializerProvider sp, DeserializerProvider dp, SerializationConfig sconfig, DeserializationConfig dconfig)
ObjectMapper(SerializerFactory sf) 不推荐使用。使用其他构造来代替; 注意,可以设置序列化工厂setSerializerFactory(org.codehaus.jackson.map.SerializerFactory)
这个类继承了以下类方法:
java.lang.Object
测试类基本代码如下
* @project java
* @package
* @file Jackson.java
* @version 1.0
public class Jackson {
* Class Descripton goes here.
* @class Jackson
* @version 1.0
public static JsonGenerator jsonGenerator =
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();
//readJson2Array();
//writeArray2Json(array);
//writeJson2List();
//writeEntity2Json(student);
writeJson2Entity();
//writeMap2Json(stuMap);
//writeList2Json(stuList1);
} catch (IOException e) {
e.printStackTrace();
* &code&writeEntity2Json&/code&
* @description: TODO(实体类转换成json)
* @param object
* @throws IOException
public static void writeEntity2Json(Object object) throws IOException {
mapper.writeValue( new File("D:\\developSoft\\aaadowload\\testjson1\\lib\\aa.txt"),object );
mapper.writeValue( System.out,object );
* &code&writeArray2Json&/code&
* @description: TODO(数组转换成json数组)
* @param object
* @throws IOException
public static void writeArray2Json(Object object) throws IOException {
// writeValue具有和writeObject相同的功能
mapper.writeValue( new File("D:\\developSoft\\aaadowload\\testjson1\\lib\\aa.txt"),object );
mapper.writeValue(System.out,object );
* &code&writeMap2Json&/code&
* @description: TODO(map对象转换成json对象)
* @param object
* @throws IOException
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:\\developSoft\\aaadowload\\testjson1\\lib\\aamap.txt"),object );
mapper.writeValue( System.out , object );
* &code&writeList2Json&/code&
* @description: TODO(list转换成json)
* @param object
* @throws IOException
public static void writeList2Json(Object object) throws IOException {
System.out.println("==&"+mapper.writeValueAsString(object));
mapper.writeValue( new File("D:\\developSoft\\aaadowload\\testjson1\\lib\\aamap.txt"),object );
mapper.writeValue( System.out , object );
* &code&writeJson2Entity&/code&
* @description: TODO(json转换成实体)
* @throws IOException
public static void writeJson2Entity() throws IOException {
System.out.println("json串转换成entity-------------");
File file = new File("D:\\developSoft\\aaadowload\\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());
* &code&writeJson2List&/code&
* @description: TODO(json专程list对象)
* @throws IOException
public static void writeJson2List() throws IOException {
System.out.println("json串转换成entity-------------");
File file = new File("D:\\developSoft\\aaadowload\\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\"}]";
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\"}]";
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}}
大家逐个自己试试吧& ,上面也是我的测试代码
您可能感兴趣的文章:
大家感兴趣的内容
12345678910
最近更新的内容
常用在线小工具

我要回帖

更多关于 顶层对象非常复杂 的文章

 

随机推荐