java与json,一篇就够了

时间:2024-11-13 16:37:50

本示例使用的json包为阿里的fastjson

首先写三个工具类(seter和geter方法省略,自行补上):

 /**
* 屏幕实体类
*/
public class Screen { private String resolution; // 分辨率
private String size; // 显存大小 }
 /**
* 内存条实体类
*/
public class Memory { private String size; // 大小
private String brand; // 品牌 }
 /**
* 电脑实体类
*/
public class Computer { private int id; // id
private String brand; // 品牌
private Double price; // 价格
private Screen screen; // 屏幕
private List<Memory> memory; // 内存条 }

测试类,直接上代码:

 /**
* 测试类
*/
public class T01 { public static void main(String[] args) {
// 1. 《自定义对象》转《json》
Computer c1 = getComputer();
JSONObject obj = JSONObject.parseObject(JSONObject.toJSONString(c1));
System.out.println(obj);
System.out.println("---------------------------------------------------------------------------"); // 2. 《json》转《自定义对象》
String str = obj.toJSONString();
Computer c2 = JSONObject.parseObject(str, Computer.class);
System.out.println(c2.toString());
System.out.println("---------------------------------------------------------------------------"); // 3. 《列表》转《JSONArray》
List<Computer> computers = getList();
JSONArray ja = JSON.parseObject(JSONArray.toJSONString(computers), JSONArray.class);
System.out.println(ja.toJSONString());
System.out.println("---------------------------------------------------------------------------"); // 4. 《JSONArray》转《列表》
List<Computer> list = JSONArray.parseArray(ja.toJSONString(), Computer.class);
list.forEach(System.out::println);
System.out.println("---------------------------------------------------------------------------"); // 5. 《数组》转《JSONArray》
// 用Arrays的asList方法将数组转换成List,然后按照步骤3转换就可以了
List<Memory> ms = Arrays.asList(new Memory[] { new Memory("8G", "金士顿"), new Memory("4G", "三星") });
ms.forEach(System.out::println);
System.out.println("---------------------------------------------------------------------------"); // 6. 《JSONArray》转《数组》
Computer[] cs = new Computer[list.size()];
list.toArray(cs); // 先按照步骤4将JSONArray转成list,再转成数组
for (Computer computer : cs) {
System.out.println(computer);
}
} private static List<Computer> getList() {
List<Memory> ms1 = Arrays.asList(new Memory[] { new Memory("8G", "金士顿"), new Memory("4G", "三星") });
Screen s1 = new Screen("1024*768", "16G");
Computer c1 = new Computer(1, "戴尔", 5678.9, s1, ms1); List<Memory> ms2 = Arrays.asList(new Memory[] { new Memory("16G", "惠普"), new Memory("8G", "森海") });
Screen s2 = new Screen("1024*768", "8G");
Computer c2 = new Computer(2, "联想", 1234.5, s2, ms2); List<Memory> ms3 = Arrays.asList(new Memory[] { new Memory("32G", "联想"), new Memory("8G", "纽曼") });
Screen s3 = new Screen("1024*768", "16G");
Computer c3 = new Computer(3, "苹果", 4567.8, s3, ms3); return Arrays.asList(new Computer[] { c1, c2, c3 });
} private static Computer getComputer() {
List<Memory> ms = Arrays.asList(new Memory[] { new Memory("16G", "金士顿"), new Memory("8G", "三星") });
return new Computer(7, "外星人", 12345.689, new Screen("1024*768", "16G"), ms);
} }