jackson是一款通用的json序列化和反序列化的类库。
json是一种通用的数据传输格式,和xml一样,xml也是文本,但是涉及到DTD和scheme等文件约束,让人头大。json也是在这种背景下面出现的。xml的解析主要有dom和sax解析,dom比较通用,sax只能查询,查询性能好。
ObjectMapper有两个主要方法来操作json的
writeValueAsString(Object object)把对象转换为json
readValue(String str,Class clz)把对象转化为对应的类
public class Person {
//省略tostring和getset
private String name;
private int age;
private List<String> list;
private Map<String, String> map;
public Person() {
}
public Person(String name, int age, List<String> list, Map<String, String> map) {
this.name = name;
this.age = age;
this.list = list;
this.map = map;
}
}
public class Mains {
private static final ObjectMapper objectMapper = new ObjectMapper();
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("qqq");
list.add("www");
list.add("ddd");
Map<String, String> map = new HashMap<>();
map.put("names1", "aaa");
map.put("names2", "bbb");
map.put("names3", "ccc");
Person zhouqijiang = new Person("zhouqijiang", 360, list, map);
String s = toJosn(zhouqijiang);
jsonToObject(s, Person.class);
jsonToMap(s);
}
//把对象转换为json
public static String toJosn(Object object) {
try {
String s = objectMapper.writeValueAsString(object);
System.out.println(s);
return s;
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
//json转化为对象
public static void jsonToObject(String str, Class clz) {
try {
Object o = objectMapper.readValue(str, clz);
System.out.println(o);
} catch (IOException e) {
e.printStackTrace();
}
}
//json转化为Map
public static void jsonToMap(String str) {
try {
Map<String, Object> map = objectMapper.readValue(str, Map.class);
Set<Map.Entry<String, Object>> entries = map.entrySet();
for (Map.Entry<String, Object> entry : entries) {
System.out.println(entry.getKey() + " " + entry.getValue());
if (entry.getValue() instanceof Map) {
Map<String, String> value = (Map) entry.getValue();
for (String key : value.keySet()) {
System.out.println(key+" "+value.get(key));
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
上面的是一个自定义的javabean对象和json之间的操作
下面讲一下,对集合的操作,以List为例
public static void main(String[] args) {
List<Book> list = new ArrayList<>();
Book aa = new Book("aa", 12);
Book bb = new Book("bb", 13);
Book cc = new Book("cc", 14);
list.add(aa);
list.add(bb);
list.add(cc);
try {
final String s = objectMapper.writeValueAsString(list);
System.out.println(s);
List<Book> o = objectMapper.readValue(s, new TypeReference<List<Book>>() {});
o.forEach(System.out::println);
} catch (Exception e) {
e.printStackTrace();
}
}
//输出结果
[{"name":"aa","age":12},{"name":"bb","age":13},{"name":"cc","age":14}]
Book(name=aa, age=12)
Book(name=bb, age=13)
Book(name=cc, age=14)
上面的使用的List举例子的
下面的是对map的操作
destMap = mapper.readValue(jsonData, new TypeReference<Map<Integer, RbtCounter>>(){});
网友评论