Json字符串、Json对象、java对象之间的转换

版权声明:版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_37465368/article/details/82889703

JSONObject 不知道哪来的那么多的,又是alibaba的,又是org.json,又是net.minidev.json,统统都是废物

在这里全部用的: import net.sf.json.JSONObject;

反正在转换方面最有效的还是JSONObject.fromObject。


话不多说,上例子

package com.sky.hrpro.service;

import com.sky.hrpro.entity.TestEntity;
import net.sf.json.JSONObject;

/**
 * @Author: CarryJey
 * @Date: 2018/9/28 19:26:33
 */
public class Test {

    //通过实体类转换成json
    public static void BeanToJson(Object object){

        JSONObject js = JSONObject.fromObject(object);
        System.out.println(js);
    }


    public static void parseJson(String json){
        //先将string串转为json对象
        JSONObject js = JSONObject.fromObject(json);
        System.out.println(js);

        //再将json对象转换为实体对象
        TestEntity testEntity = (TestEntity)JSONObject.toBean(js,TestEntity.class);
        System.out.println(testEntity);

    }

    public static void main(String args[]){

        TestEntity testEntity = new TestEntity();
        testEntity.setId(1);
        testEntity.setName("abc");
        testEntity.setAge(23);

        String json = "{\"age\":23,\"id\":1,\"name\":\"abc\"}";

        BeanToJson(testEntity);
        parseJson(json);
    }

}

输出结果:

net.sf.json.JSONObject依赖包

http://mvnrepository.com/artifact/net.sf.json-lib/json-lib/2.4

<!--JSON转换所需的依赖包net.sf.json-lib/json-lib-->
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
            <classifier>jdk15</classifier>
        </dependency>

猜你喜欢

转载自blog.csdn.net/qq_37465368/article/details/82889703