Junit、Json和kv结构的相互转化

导包代码所在网站: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);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值