导包代码所在网站:https://mvnrepository.com/
一、Junit
在prom.xml中导入代码,刷新下载
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
</dependency>
运行时不需要main方法
若代码左侧没有运行的绿色小三角,把Junit的插件打开。
@Test:表示正在运行,
@before: 表示运行在前
@after:表示运行在后
二、Json和kv结构的相互转化
1、谷歌实现
导包Gson
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.9.0</version>
</dependency>
public class JsonTest {
public static void main(String[] args) {
//JSON:String中存储的是HashMap{k1:v1,k2:v2...}
//通过第三方工具Gson 把json解析成kv结构就可以通过k获取v。
String str="{\"id\":1001,\"name\":\"zs\",\"age\":20,\"sex\":\"男\"}";
System.out.println(str);
/*
创键操作json的类,通过这个对象,把json转化为kv
*/
Gson gson=new Gson();
Student student=gson.fromJson(str, Student.class);
System.out.println(student.toString()); //当str中参数与student类中变量名不一致是,默认student中变量获取的是null值。
//当参数的数据类型和student类中不一致时会报错。如果是数值的String类型是可以和int相互转换的。
/*
对象转换成json
*/
String s = gson.toJson(student);
System.out.println(s);
}
}
{"id":1001,"name":"zs","age":20,"sex":"男"}
Student{id=1001, name='zs', age=20, sex='男'}
{"id":1001,"name":"zs","age":20,"sex":"男"}
2、阿里巴巴实现
导包Fastjson
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.79</version>
</dependency>
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
public class FastJsonTest {
public static void main(String[] args) {
String str="{\"id\":1001,\"name\":\"zs\",\"age\":20,\"sex\":\"男\"}";
/**
* 将json字符串转化为kv结构 将json字符串转化为json对象
*/
JSONObject jsonObject = JSON.parseObject(str);
Object name = jsonObject.get("name");
System.out.println(name);
Object id = jsonObject.get("id");
System.out.println(name+"----"+id);
/**
* 将json对象转化为json字符串
*/
Object o = JSON.toJSON(jsonObject);
System.out.println(o);
/**
* 转化为一个自己创建的类
*/
Student student = JSON.parseObject(str, Student.class);
System.out.println(student);
/**
* 对象转化为json字符串
*/
Object o1 = JSON.toJSON(student);
System.out.println(o1);
}
}