目录
场景
作用
依赖库
工具类
工具类测试
将json格式的字符串转化成对象
将对象转化成json格式的字符串
总结:
参考:
最近接触远程调用服务,经常用json传输及用到了xml解析发现自己基础的薄弱环节。
Jackson可以轻松的将Java对象转换成json对象和xml文档,同样也可以将json、xml转换成Java对象。
com.fasterxml.jackson.core
jackson-core
2.9.2
com.fasterxml.jackson.core
jackson-databind
2.9.2
com.fasterxml.jackson.core
jackson-annotations
2.9.2
package org.wxy.com.util;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.wxy.com.model.AccountBean;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
public class JsonUtils {
private static ObjectMapper mapper = new ObjectMapper();
/**
*
* @description :使用JsonGenerator将对象转化成json字符串
* @author wu xin yang
* @param bean
* @return
*/
public static void beanToJson(Object bean){
JsonGenerator jsonGenerator = null;
try {
jsonGenerator =mapper.getFactory().createGenerator(System.out, JsonEncoding.UTF8);
jsonGenerator.writeObject(bean);
} catch (IOException e) {
e.printStackTrace();
};
}
/**
*
* @description :使用ObjectMapper将对象转化成json字符串
* @author wu xin yang
* @param bean
* @return
*/
public static void beanToJsonByObjectMapper(Object bean){
try {
mapper.writeValue(System.out, bean);
} catch (IOException e) {
e.printStackTrace();
};
}
/**
* @desc:用一个指定的key,value为输人的对象格式的json输出
* @param bean
* @return infos:[array]
*/
public static String writeObjectField(String key,String[] arr){
JsonGenerator jsonGenerator = null;
try {
System.out.println("jsonGenerator");
jsonGenerator =mapper.getFactory().createGenerator(System.out, JsonEncoding.UTF8);
//必须添加jsonGenerator.writeStartObject();
jsonGenerator.writeStartObject();
jsonGenerator.writeObjectField(key, arr);//infos:[array]
jsonGenerator.writeEndObject();
} catch (IOException e) {
e.printStackTrace();
};
return null;
}
/**
* @desc:输出指定格式的json(测试未成功,没有数据输出)
* @param bean
* @return infos:[array]
*/
public static String writeObject(){
JsonGenerator jsonGenerator = null;
try {
System.out.println("jsonGenerator");
jsonGenerator =mapper.getFactory().createGenerator(System.out, JsonEncoding.UTF8);
//Object
jsonGenerator.writeStartObject();//{
jsonGenerator.writeObjectFieldStart("user");//user:{
jsonGenerator.writeStringField("name", "jackson");//name:jackson
jsonGenerator.writeBooleanField("sex", true);//sex:true
jsonGenerator.writeNumberField("age", 22);//age:22
jsonGenerator.writeEndObject();//}
System.out.println();
jsonGenerator.writeArrayFieldStart("infos");//infos:[
jsonGenerator.writeNumber(22);//22
jsonGenerator.writeString("this is array");//this is array
jsonGenerator.writeEndArray();//]
jsonGenerator.writeEndObject();
} catch (IOException e) {
e.printStackTrace();
};
return null;
}
/**
* @desc:输出指定的json
* @param bean
* @return infos:[array]
*/
public static String writeStringObject(String str){
JsonGenerator jsonGenerator = null;
try {
System.out.println("jsonGenerator");
jsonGenerator =mapper.getFactory().createGenerator(System.out, JsonEncoding.UTF8);
jsonGenerator.writeBinary(str.getBytes());
//boolean
jsonGenerator.writeBoolean(true);
//null
jsonGenerator.writeNull();
//float
jsonGenerator.writeNumber(2.2f);
//char
jsonGenerator.writeRaw("c");
//String
jsonGenerator.writeRaw(str, 5, 10);
//String
jsonGenerator.writeRawValue(str, 5, 5);
//String
jsonGenerator.writeString(str);
jsonGenerator.writeTree(JsonNodeFactory.instance.pojoNode(str));
System.out.println();
} catch (IOException e) {
e.printStackTrace();
};
return null;
}
//===================json字符串转对象==================mapper.readValue==================
/**
* 仅支持这种格式带有中括号【】:[{"a":a,"b":b},{"c":c,"d":"d"}]
* @desc:将json格式字符串转化为List>对象
* @param jsonStr
* @return
*/
public static List> readJson2List(String jsonStr){
List> list=null;
try {
list = mapper.readValue(jsonStr, List.class);
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
/**
* 仅支持这种格式:{"a":a,"b":b}
* @desc:将json格式字符串转化为map对象
* @param jsonStr
* @return
*/
public static Map readJson2Map(String jsonStr){
Map map=null;
try {
map = mapper.readValue(jsonStr, Map.class);
} catch (IOException e) {
e.printStackTrace();
}
return map;
}
}
以下几个方法不够通用,故从工具类中剔除
/**
* 仅支持这种格式带有中括号【】:[{"a":a,"b":b},{"c":c,"d":"d"}]
* @desc:将json格式字符串转化为List对象
* @param jsonStr
* @return
*/
public static List readJson2ListBean(String jsonStr){
List list=null;
try {
list = mapper.readValue(jsonStr, List.class);
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
/**
*
* 字符串格式必须包含中括号[{"a":"a"},{"b":"b"},{"c":"c"}]
* @desc:将字符串json格式转化为 数组
* @param jsonStr
* @return
* 问题:不够通用,如果AccountBean[].class能作为参数传进来就更好了
*/
public static Object[] readJson2Array(String json) {
AccountBean[] arr = null;
try {
arr = mapper.readValue(json, AccountBean[].class);
} catch (IOException e) {
e.printStackTrace();
}
return arr;
}
测试一:将json格式的字符串转化成Map对象
@Test
public void readJson2Map() {
String json = "{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"}";
Map readJson2Map = JsonUtils.readJson2Map(json);
JsonUtils.beanToJson(readJson2Map);
}
测试二:将json格式的字符串转化成List
@Test
public void readJson2List() {
String json = "[{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}]";
List> readJson2List = JsonUtils.readJson2List(json);
JsonUtils.beanToJson(readJson2List);
}
测试三:将json格式的字符串转化成List
@Test
public void readJson2ListBean() {
String json = "[{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}]";
List readJson2List = JsonUtils.readJson2ListBean(json);
JsonUtils.beanToJson(readJson2List);
}
测试四:将json格式的字符串转化成Bean[ ]对象(该方法不够通用,放到工具类中不合适)
@Test
public void readJson2Array() {
String json = "[{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}]";
AccountBean[] readJson2Array = (AccountBean[]) JsonUtils.readJson2Array(json);
JsonUtils.beanToJson(readJson2Array);
}
测试一:将对象bean转化为json格式字符串
@Test
public void testBean2Json(){
AccountBean bean = new AccountBean();
bean.setAddress("china-Guangzhou");
bean.setEmail("[email protected]");
bean.setId(1);
bean.setName("hoojo");
JsonUtils.beanToJson(bean);
}
测试二:将对象Map转化为json格式字符串
@Test
public void testMap2Json(){
Map map = new HashMap();
AccountBean bean = new AccountBean();
bean.setAddress("china-Beijin");
bean.setEmail("[email protected]");
map.put("name", "hoojo");
map.put("account", bean);
JsonUtils.beanToJson(map);
}
测试三:将对象List转化为json格式字符串
@Test
public void testList2Json(){
List list= new ArrayList();
AccountBean bean = new AccountBean();
bean.setAddress("china-Beijin");
bean.setEmail("[email protected]");
list.add(bean);
JsonUtils.beanToJson(list);
}
1.jackson将对象输出成json格式字符串两种形式
形式一 :通过ObjectMapper的writeValue()方法,输出流实际应用中可以通过Response建立在浏览器中输出
mapper.writeValue(System.out, bean);
形式二:JsonGenerator的writeObject()方法
jsonGenerator.writeObject(bean);
2.JsonGenerator的建立依赖于ObjectMapper,但是ObjectMapper可单独使用
jsonGenerator =mapper.getFactory().createGenerator(System.out, JsonEncoding.UTF8);
3.jackson将json格式字符串转化成对象,主要通过ObjectMapper
mapper.readValue()
4.springMVC默认集成了jackson
https://blog.csdn.net/oydaybreak/article/details/45170557
https://blog.csdn.net/zzti_erlie/article/details/79779253
=======================================更新=========================================================
以上工具类写了很多,看了大佬的一些博客工具类就整了两行就解决了,惭愧!!
/**
* Serialize any Java value as a String.
*/
public static String generate(Object object) throws JsonProcessingException {
return mapper.writeValueAsString(object);
}
/**
* Deserialize JSON content from given JSON content String.
*/
public static T parse(String content, Class valueType) throws IOException {
return mapper.readValue(content, valueType);
}
测试:将对象转化成json
@Test
public void generate() {
List list= new ArrayList();
AccountBean bean = new AccountBean();
bean.setAddress("china-Beijin");
bean.setEmail("[email protected]");
list.add(bean);
try {
String aaa = JsonUtils.generate(list);
System.out.println(aaa);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
测试:将json格式字符串转化成指定对象
@Test
public void parse() throws IOException {
try {
String json = "[{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}]";
AccountBean[] readJson2Array1 = (AccountBean[]) JsonUtils.parse(json,AccountBean[].class);
List>readJson2Array = (List>) JsonUtils.parse(json,List.class);
JsonUtils.beanToJson(readJson2Array1);
JsonUtils.beanToJson(readJson2Array);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
参考:https://blog.csdn.net/weixin_44048532/article/details/86647880