直接上代码

 package com.demo.jackson.utils;

 import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils; @Slf4j
public class JsonUtil {
private static ObjectMapper objectMapper = new ObjectMapper();
static {
//忽略 在json字符串中存在,但是在java对象中不存在对应属性的情况。防止错误
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
} /**
* 对象转换成Sting
* @param obj
* @param <T>
* @return
*/
public static <T> String obj2String(T obj){
if (obj == null) {
return null;
}
try {
return obj instanceof String ? (String) obj : objectMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
System.out.println("Parse Object to String error");
e.printStackTrace();
return null;
}
}
/**
* 规范地将对象转换成Sting
* @param obj
* @param <T>
* @return
*/
public static <T> String obj2StringPretty(T obj){
if(obj == null){
return null;
}
try {
return obj instanceof String ? (String)obj : objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
} catch (Exception e) {
log.warn("Parse Object to String error",e);
return null;
}
} /**
* String转换成obj对象
* @param str
* @param clazz
* @param <T>
* @return
*/
public static <T> T str2Obj(String str, Class<T> clazz){
if(str==null){
return null;
}
try {
return clazz.equals(String.class) ? (T) str : objectMapper.readValue(str, clazz);
} catch (Exception e) {
e.printStackTrace();
return null;
}
} /**
* String转换成对象
* @param str
* @param typeReference
* @param <T>
* @return
*/
public static <T> T string2Obj(String str, TypeReference<T> typeReference){
if(StringUtils.isEmpty(str) || typeReference == null){
return null;
}
try {
return (T)(typeReference.getType().equals(String.class)? str : objectMapper.readValue(str,typeReference));
} catch (Exception e) {
log.warn("Parse String to Object error",e);
return null;
}
} /**
* String转换成对象
* @param str
* @param collectionClass
* @param elementClasses
* @param <T>
* @return
*/
public static <T> T string2Obj(String str, Class<?> collectionClass, Class<?>... elementClasses){
JavaType javaType = objectMapper.getTypeFactory().constructParametricType(collectionClass,elementClasses);
try {
return objectMapper.readValue(str,javaType);
} catch (Exception e) {
log.warn("Parse String to Object error",e);
return null;
}
}
}

测试:

 package com.demo.jackson.test;

 import com.demo.jackson.entity.Student;
import com.demo.jackson.utils.JsonUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test; import java.util.*; @SuppressWarnings("ALL")
public class JacksonTest {
/**
* 序列化
*/
@Test
public void test01(){
Student s = new Student();
s.setName("cjj");
s.setAge(22);
s.setProfileImageUrl("link");
String s1 = JsonUtil.obj2String(s);
System.out.println(s1); Map<String, List<Integer>> map = new HashMap<>();
map.put("a", Arrays.asList(1, 2, 3));
map.put("b", Arrays.asList(1, 2, 3));
String result1 = JsonUtil.obj2StringPretty(map);
System.out.println(result1);
} /**
* 反序列化
*/
@Test
public void Test02(){
String str = "{\"name\":\"name\",\"age\":10,\"profileImageUrl\":\"link\"}";
Student student = JsonUtil.str2Obj(str, Student.class);
System.out.println(student);
}
@Test
public void test03() throws Exception { Student student1 = new Student();
student1.setAge(10);
student1.setName("name1");
student1.setProfileImageUrl("link1"); Student student2 = new Student();
student2.setAge(20);
student2.setName("name2");
student2.setProfileImageUrl("link2"); List<Student> studentList = new ArrayList<>();
studentList.add(student1);
studentList.add(student2);
String result = JsonUtil.obj2String(studentList);
// [{"name":"name1","age":10,"profileImageUrl":"link1"},{"name":"name2","age":20,"profileImageUrl":"link2"}]
System.out.println(result); List<Student> finalList = JsonUtil.string2Obj(result, new TypeReference<List<Student>>() {});
// [{name=name1, age=10, profileImageUrl=link1}, {name=name2, age=20, profileImageUrl=link2}]
System.out.println(finalList);
}
@Test
public void test04() throws Exception { Student student1 = new Student();
student1.setAge(10);
student1.setName("name1");
student1.setProfileImageUrl("link1"); Student student2 = new Student();
student2.setAge(20);
student2.setName("name2");
student2.setProfileImageUrl("link2"); List<Student> studentList = new ArrayList<>();
studentList.add(student1);
studentList.add(student2);
String result = JsonUtil.obj2String(studentList);
// [{"name":"name1","age":10,"profileImageUrl":"link1"},{"name":"name2","age":20,"profileImageUrl":"link2"}]
System.out.println(result); List<Student> finalList = JsonUtil.string2Obj(result, List.class, Student.class);
// [{name=name1, age=10, profileImageUrl=link1}, {name=name2, age=20, profileImageUrl=link2}]
System.out.println(finalList);
}
@Test
public void jsonProperty() throws Exception { String str = "{\"name\":\"name\",\"age\":10,\"setImage\":\"link\"}";
Student student1 = JsonUtil.string2Obj(str, Student.class);
// name
System.out.println(student1.getName());
//
System.out.println(student1.getAge());
// link
System.out.println(student1.getProfileImageUrl());
// {"name":"name","age":10,"getImage":"link"}
System.out.println(JsonUtil.obj2String(student1));
} /**
* 除了将json转为对象外,还可以用Tree Mode方式解析JSON,全程无脑操作,
* 除了一些特别复杂的JSON,或者只取JSON中的一部分,千万不要用这种二B方式解析JSON。
* 正确的方式是将JSON直接转为对象。
* @throws Exception
*/
@Test
public void parseJson() throws Exception {
String jsonStr = "{\"name\":\"zhansan\",\"age\":100,\"schools\":[{\"name\":\"tsinghua\",\"location\":\"beijing\"},{\"name\":\"pku\",\"location\":\"beijing\"}]}"; ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(jsonStr); String name = jsonNode.get("name").asText();
int age = jsonNode.get("age").asInt();
// name is zhansan age is 100
System.out.println("name is " + name + " age is " + age); JsonNode schoolsNode = jsonNode.get("schools");
for (int i = 0; i < schoolsNode.size(); i++) {
String schooleName = schoolsNode.get(i).get("name").asText();
String schooleLocation = schoolsNode.get(i).get("location").asText();
// schooleName is tsinghua schooleLocation is beijing
// schooleName is pku schooleLocation is beijing
System.out.println("schooleName is " + schooleName + " schooleLocation is " + schooleLocation);
}
}
}

jackson的应用的更多相关文章

  1. jackson简单使用,对象转json,json转对象,json转list

    添加jackson依赖: // https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core compile g ...

  2. Jackson 通过自定义注解来控制json key的格式

    Jackson 通过自定义注解来控制json key的格式 最近我这边有一个需求就是需要把Bean中的某一些特殊字段的值进行替换.而这个替换过程是需要依赖一个第三方的dubbo服务的.为了使得这个转换 ...

  3. Jackson的简单用法

    文章版权由作者李晓晖和博客园共有,若转载请于明显处标明出处:http://www.cnblogs.com/naaoveGIS/. 1简介 Jackson具有比较高的序列化和反序列化效率,据测试,无论是 ...

  4. jackson error 含义log

    1. 反序列化失败,类型不匹配 Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not deserial ize ...

  5. jackson annotations注解详解

    jackson中常用到的注解 猛击下面的连接地址 http://blog.csdn.net/sdyy321/article/details/40298081

  6. jackson官方快速入门文档

    官方地址: http://jackson.codehaus.org/ http://wiki.fasterxml.com/JacksonInFiveMinutes http://wiki.faster ...

  7. Jackson将json字符串转换成泛型List

    Jackson,我感觉是在Java与Json之间相互转换的最快速的框架,当然Google的Gson也很不错,但是参照网上有人的性能测试,看起来还是Jackson比较快一点 Jackson处理一般的Ja ...

  8. 使用Jackson解析Json示例

    原文http://blog.csdn.net/gebitan505/article/details/17005735 custom.json: {     "country":&q ...

  9. Json解析工具Jackson(使用注解)

    原文http://blog.csdn.net/nomousewch/article/details/8955796 接上一篇文章Json解析工具Jackson(简单应用),jackson在实际应用中给 ...

  10. Json解析工具Jackson(简单应用)

    原文http://blog.csdn.net/nomousewch/article/details/8955796 概述 Jackson库(http://jackson.codehaus.org),是 ...

随机推荐

  1. 51全志R58平台Android4.4下Camera的HAL层修改

    51全志R58平台Android4.4下Camera的HAL层修改 2018/11/7 15:20 版本:V1.0 开发板:SC5806 1.系统编译: (略) 2.全志R58平台Android4.4 ...

  2. mysql 判断字符串是否为其他字符串的子集

    1.mysql 提供单个用逗号隔开判断某个字符串是否包含在其他字符串的之内:FIND_IN_SET('需要匹配的字符串','源字符串'); demo: select FIND_IN_SET('111' ...

  3. leetcode:single-number-ii(Java位运算)

    题目 Given an array of integers, every element appears three times except for one. Find that single on ...

  4. leetcode_486. Predict the Winner

    https://leetcode.com/problems/predict-the-winner/ 题目描述:给定一个非负的积分数组,玩家1可以从数组两端任取一个积分,接着玩家2执行同样的操作,直至积 ...

  5. Leetcode_638.Shopping Offers

    https://leetcode.com/problems/shopping-offers/ In LeetCode Store, there are some kinds of items to s ...

  6. Linux C动态链接库实现一个插件例子

    实现一个简单的计算动态链接库:升级动态链接库后,在不重新编译主程序的情况下,直接生效. lib库: #cat math.c #include <stdio.h> int add(int x ...

  7. DHCP和PXE

    继续学习,Let's go!DHCP和PXE都是什么呢?如果非科班出身,可能一脸懵逼,好多东西需要去学习了,真的,继续学吧,付出不一定会有回报,不付出肯定就是等死了,呵呵! 一.DHCP 真正需要手动 ...

  8. jquery.form.min.js

    /*! * jQuery Form Plugin * version: 3.51.0-2014.06.20 * Requires jQuery v1.5 or later * Copyright (c ...

  9. (C/C++学习)17.bitset(位操作)

    说明:bitset 就像 vector 一样,是 C++ 的一个类模板库,用来对一个数的二进制位进行管理.判断等操作,使用时需要包含头文件 #include<bitset>. 1.声明及定 ...

  10. Spring 实现 IoC

    理解 “ 控制反转(IoC)”   控制反转(IoC):用白话来讲,就是由 Spring 容器控制程序中类与类之间的关系,而非传统实现中,由程序代码直接操控.这也就是所谓 “控制反转” 的概念所在:控 ...