JSONObject

JSONObject是一种类似于JSON格式的key-value的数据结构,我们可以通过其方法put给JSONObject对象添加key-value格式的字符串,还是比较方便的,后续还可以转换成JSONxxx的其他类型,都是很方便的.

刚刚入坑的公司是SSM框架体系,SpringMVC的相应返回值是Map<String,Object>,所以用的比较频繁,刚入职场的菜鸟我觉得应该还是比较常用的吧

pom文件(依赖/包): 我们使用的版本是:1.2.28,还是根据需要来锁定版本吧

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.28</version>
</dependency>

 bean实体类转换JSONObject:

Emp emp = new Emp();
        emp.setId(1);
        emp.setName("小张");
        //转换
        JSONObject jsonObject = JSONObject.parseObject(emp.toString());

原生JSONObject bean对象

//原始的原生代码
//原生的bean对象也是key-value格式的,我们可以就当做是Map集合,只不过是JSON格式的
JSONObject object = new JSONObject();
object.put("A","a");
object.put("B","b");
System.out.println("object = " + object);

普通的字符串转换

        //普通String->JSONObject的转换
        String str = "逻辑需求";
        JSONObject jsonStr = JSONObject.parseObject(str);

list集合转换JSONArray

        /list集合转换JSONOArray
        //这个也是我们比较常用的
        List<Emp> list = new ArrayList<Emp>();
        Emp empTwo = new Emp();
        empTwo.setId(2);
        empTwo.setName("小李");
        Emp empThree = new Emp();
        empThree.setId(3);
        empThree.setName("小王");
        Collections.addAll(list,empTwo,empThree);
        JSONArray jsonArray = JSONArray.parseArray(list.toString());

JSONArray和JSOnObject的相互转换,也谈不上转换,我们可以理解成容器

        //JSONObject&JSONArray的转换
        JSONObject jsonObj = new JSONObject();
        JSONArray jsonArr = new JSONArray();
        //arr->obj的转换,可以响应给前端
        JSONObject fluentPut = jsonObj.fluentPut("响应key", jsonArr);
        //obj->arr的转换,亦可响应给前段
        JSONArray objects = jsonArr.fluentAdd(jsonObj);

JSONObj还是比较常使用的,我刚接触的时候就非常喜欢,我们可以用在返回给前段key-value,或者建立省级联动的json字符串,还是比较方便的,第一次发文章如有错误还请指出,多谢.

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值