Xml和json是为了解决网络数据传输问题,假如服务端用java语言,而前台可以用其它语言。Json 就是解决不同语言之间对象转换的问题。Xml也是一种语言,只是它的传输效率没有json那么高,但它的可读性比json好。
fastJson 和 Gson是json转换常用工具,下面是一些常用方法
//用gson将对象转换成json
public class Demo1 {
public static void main(String[] args) {
Gson gson = new Gson();
//用gson转换book
Book book = new Book("1","红苹果","又大又甜");
String s = gson.toJson(book);
System.out.println(s);
}
}
//通过Gson将字符转换
public class Demo2 {
public static void main(String[] args) {
//1. 创建Gson对象
Gson gson = new Gson();
//2. 转换 : {"id":"100","name":"金苹果","info":"种植苹果真辛苦"}
Book b= gson.fromJson("{\"id\":\"100\",\"name\":\"金苹果\",\"info\":\"种植苹果真辛苦\"}",Book.class);
System.out.println(b.getId());
System.out.println(b.getName());
System.out.println(b.getInfo());
}
}
//转换json中的数组
public class Demo3 {
public static void main(String[] args) {
Gson gson = new Gson();
//2. 转换 : {"id":"100","name":"金苹果","info":"种植苹果真辛苦","page":["锄禾日当午","汗滴禾下土","嘿嘿嘿嘿嘿"]}
HashMap hashMap = gson.fromJson(" {\"id\":\"100\",\"name\":\"金苹果\",\"info\":\"种植苹果真辛苦\",\"page\":[\"锄禾日当午\",\"汗滴禾下土\",\"嘿嘿嘿嘿嘿\"]}", HashMap.class);
List page = (List)hashMap.get("page");
System.out.println(page.get(1));
}
}
//fastJSON : 对象转json
public class Demo4 {
public static void main(String[] args) {
Book book=new Book("1002","古诗","春眠不觉晓,处处蚊子咬。");
String json = JSON.toJSONString(book);
System.out.println(json);
}
}
//FastJSON JSON字符串转Book对象
public class Demo5 {
public static void main(String[] args) {
Book book = JSON.parseObject("{\"id\":\"1002\",\"info\":\"春蚕到死丝方尽,蜡炬成灰泪始干。\",\"name\":\"唐诗三百首\"}",Book.class);
System.out.println(book.getId());
System.out.println(book.getInfo());
}
}
//FastJSON 数组转集合
public class Demo6 {
public static void main(String[] args) {
List<String> strings = JSON.parseArray("[\"一二三\",\"二三四\",\"三四五\"]", String.class);
System.out.println(strings.get(2));
}
}