最近工作中用到的jackjson中的一些简单使用,整理了以下示例,便于以后学习使用。
package com.sgai.test;
import java.io.Reader;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import cn.hutool.json.JSONObject;
//json学习链接https://blog.csdn.net/lin443514407lin/article/details/85262479
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY,getterVisibility = JsonAutoDetect.Visibility.NONE)
public class TestSYJson {
public static JSONObject toLowerKey(Map jso) {
Map resultMap = new HashMap ();
Set<String> sets = jso.keySet();
for (String key : sets) {
resultMap.put(key.toLowerCase(), jso.get(key));
}
JSONObject jr=new JSONObject(resultMap);
return jr;
}
public static void main(String[] args) throws Exception {
//对象
Map m=new HashMap();
m.put("OrderDetail", "rrrrr");
m.put("NameG", "wwww");
m.put("AgeG", "8888");
//把对象转化成json字符串
ObjectMapper objectMapper = new ObjectMapper().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES).setSerializationInclusion(Include.NON_NULL);
String tt=objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(m);
System.out.println("把对象转化成json字符串"+tt);
//把json字符串 转化成 javabean
Reader reader = new StringReader(tt);
Map rm = objectMapper.readValue(reader, Map.class);
rm= toLowerKey(rm);//转小写的方式
System.out.println("把字符串转化成json对象"+rm.get("OrderDetail"));
//把json字符串 转化成 json对象
JsonNode jj=objectMapper.readTree(tt);
//判断某个节点是否是array
if( jj.get("AgeG").isArray()){
//如果是array,则转化成Iterator
Iterator it= jj.get("AgeG").iterator();
}
//删除json对象中的某个节点使用ObjectNode,可以增加删除Node
ObjectNode oo=(ObjectNode)objectMapper.readTree(tt);
//删除
oo.remove( "chargedetails");
//增加普通节点
oo.put("ttt", "waoo");
//添加普通数组节
ArrayNode an=oo.putArray("treeList");
String [] treess={"apple","charry"};
for(String tree:treess){
an.add(tree);
}
System.out.println(oo);
//添加json数组节点
ArrayNode an2=oo.putArray("jsonList");
String [] treess2={"apple#read","charry#blue"};
for(String tree:treess2){
String [] tmp =tree.split("#");
Map ttm=new HashMap();
ttm.put("name", tmp[0]);
ttm.put("colour", tmp[1]);
String tmpJ=objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(ttm);
JsonNode tmpN=objectMapper.readTree(tmpJ);
an2.add(tmpN);
}
System.out.println(oo);
}
}