JSON: JavaScript Object Notation JS对象简谱 , 是一种轻量级的数据交换格式.
JAVA解析Json可以引入第三方类库 FastJson和Gjson
将对象转换为JSON字符串
导入jar包后,代码实现如下
public class GsonDemo { public static void main(String[] args) { Gson gson = new Gson(); String json = "[{\"id\":\"1\",\"name\":\"三国演义\",\"author\":\"罗贯中\",\"info\":\"东汉末年\",\"price\":\"192.0\"},{\"id\":\"2\",\"name\":\"水浒传\",\"author\":\"施耐庵\",\"info\":\"梁山好汉\",\"price\":\"192.0\"}]"; String json1 ="{\"id\":\"1\",\"name\":\"三国演义\",\"author\":\"罗贯中\",\"info\":\"东汉末年\",\"price\":\"192.0\"}"; //获取对象数组 ArrayList<Book> arrayList = gson.fromJson(json, ArrayList.class); System.out.println(arrayList); //获取单个对象 Book book = gson.fromJson(json1, Book.class); System.out.println(book); String json2 = gson.toJson(arrayList); System.out.println(json2); } }
导入jar包后,代码实现如下
public class FastJsonDemo { public static void main(String[] args) { String json = "[{\"id\":\"1\",\"name\":\"三国演义\",\"author\":\"罗贯中\",\"info\":\"东汉末年\",\"price\":\"192.0\"},{\"id\":\"2\",\"name\":\"水浒传\",\"author\":\"施耐庵\",\"info\":\"梁山好汉\",\"price\":\"192.0\"}]"; String json1 ="{\"id\":\"1\",\"name\":\"三国演义\",\"author\":\"罗贯中\",\"info\":\"东汉末年\",\"price\":\"192.0\"}"; //获取对象数组 List<Book> arrayList = JSON.parseArray(json, Book.class); System.out.println(arrayList); //获取单个对象 Book book =JSON.parseObject(json1, Book.class); System.out.println(book); //将对象转换成json字符串 String json2 =JSON.toJSONString(arrayList); System.out.println(json2); } }