从数据库中取出数据会封装到实体里面

1.实体属性与数据库字段一致 直接映射

例子:

表 group

实体 group

@Data
@Entity
public class Groupd implements Serializable{


    private static final long serialVersionUID = -4695789617580212500L;

    /**
     * 班组id
     */
    @Id
    @GeneratedValue
    public Long id;

    /**
     * 班组名
     */
    public String name;

    public Groupd() {
    }

    public Groupd(String name) {
        this.name = name;
    }
}

测试:

  @Test
    public void findAllGroup() {
        List<Groupd> result = responsitory.findAll();
        log.info("result={}", result);
        for (Groupd groupd : result) {
            log.info(groupd.name);
        }
        Assert.assertNotNull(result);
    }

注意映射的是对象 还需要转换成 json格式的字符串 才能传输到 前端使用


2.实体属性与数据库字段不一致 需要处理后映射

如果不一致加上注解来 映射

    /**
     * 班组名
     */
    @Column(name = "group_name")
    private String name;

3.后台映射的对象转成json的方法

首先说下 net.sf.json.JSONObject 和org.json.JSONObject 的差别

net.sf.json.JSONObject 依赖 需要6个jar包

jar包链接

pom

<!-- JSONObject start-->
<dependency>
   <groupId>commons-beanutils</groupId>
   <artifactId>commons-beanutils</artifactId>
   <version>1.9.3</version>
</dependency>
<dependency>
   <groupId>commons-collections</groupId>
   <artifactId>commons-collections</artifactId>
   <version>3.2.1</version>
</dependency>
<dependency>
   <groupId>commons-lang</groupId>
   <artifactId>commons-lang</artifactId>
   <version>2.6</version>
</dependency>
<dependency>
   <groupId>commons-logging</groupId>
   <artifactId>commons-logging</artifactId>
   <version>1.1.1</version>
</dependency>
<dependency>
   <groupId>net.sf.ezmorph</groupId>
   <artifactId>ezmorph</artifactId>
   <version>1.0.6</version>
</dependency>
<dependency>
   <groupId>net.sf.json-lib</groupId>
   <artifactId>json-lib</artifactId>
   <version>2.4</version>
   <classifier>jdk15</classifier><!-- jdk版本 -->
</dependency>
<!-- JSONObject end-->

为什么要加入 classifier  说明一下

../
json-lib-2.4-jdk13.jar                             2010-12-14 05:39               158091
json-lib-2.4-jdk13.jar.md5                         2012-11-27 09:40                   32
json-lib-2.4-jdk13.jar.sha1                        2012-11-27 09:21                   40
json-lib-2.4-jdk13-javadoc.jar                     2010-12-14 05:39               245414
json-lib-2.4-jdk13-javadoc.jar.md5                 2012-11-27 09:40                   32
json-lib-2.4-jdk13-javadoc.jar.sha1                2012-11-27 09:21                   40
json-lib-2.4-jdk13-sources.jar                     2010-12-14 05:39               102628
json-lib-2.4-jdk13-sources.jar.md5                 2012-11-27 09:40                   32
json-lib-2.4-jdk13-sources.jar.sha1                2012-11-27 09:21                   40
json-lib-2.4-jdk15.jar                             2010-12-14 05:39               159123
json-lib-2.4-jdk15.jar.md5                         2012-11-27 09:40                   32
json-lib-2.4-jdk15.jar.sha1                        2012-11-27 09:21                   40
json-lib-2.4-jdk15-javadoc.jar                     2010-12-14 05:39               248552
json-lib-2.4-jdk15-javadoc.jar.md5                 2012-11-27 09:40                   32
json-lib-2.4-jdk15-javadoc.jar.sha1                2012-11-27 09:21                   40
json-lib-2.4-jdk15-sources.jar                     2010-12-14 05:39               104992
json-lib-2.4-jdk15-sources.jar.md5                 2012-11-27 09:40                   32
json-lib-2.4-jdk15-sources.jar.sha1                2012-11-27 09:21                   40
json-lib-2.4.pom                                   2010-12-14 05:39                13082
json-lib-2.4.pom.md5                               2012-11-27 09:40                   32
json-lib-2.4.pom.sha1                              2012-11-27 09:21                   40

根据Maven默认组织包的结构来看,这里根本找不到json-lib-2.4.jar的包,所以也就下不下来。

没有标准的jar包,但是有扩展的,如:json-lib-2.4-jdk15.jar,所以,这里要引入classifier这个元素了,classifier元素用来帮助定义构件输出的一些附属构件。

所以,下面这里加入classifier元素来下载扩展包json-lib-2.4-jdk15.jar。

<dependency>
    <groupId>net.sf.json-lib</groupId>
    <artifactId>json-lib</artifactId>
    <version>2.4</version>
    <classifier>jdk15</classifier>
</dependency>

这样就能下载对应的附属构件了。

这里拿json-lib这个包来举例,但它已经停止更新维护了,不推荐使用,推荐使用fastjson、jackson、gson等json转换框架。


使用:

a. json-lib

1.将普通str转换成JSONObjct格式

实例:

@Test
    public void str2JSONObject() {
        String str = "{\"result\":\"success\", \"message\":\"成功!\"}";
        JSONObject json = JSONObject.fromObject(str);
        log.info(json.toString());
    }

结果:

2.将普通str转换成JSONArray

实例:

 @Test
    public void str2JSONArray() {
        String str = "{\"result\":\"success\",\"message\":\"成功!\",\"data\":[{\"name\":\"Tom\",\"age\":\"20\"}]}";
        JSONObject json = JSONObject.fromObject(str);
        System.out.println("json====》" + json);
        JSONArray jsonArray = JSONArray.fromObject(json.get("data"));
        System.out.println("jsonArray====》" + jsonArray);
    }

结果:


 java对象--》》字符串

java普通对象指的是java中的一个java bean,即一个实体类,

实例:

 @Test
    public void javaObj2JSON() {
        Student stu = new Student();
        stu.setStudentId(1);
        stu.setStudentName("张三");

        //1、使用JSONObject
        JSONObject jsonObject = JSONObject.fromObject(stu);

        //2、使用JSONArray
        JSONArray jsonArray = JSONArray.fromObject(stu);

        String strJson = jsonObject.toString();
        String strArray = jsonArray.toString();

        System.out.println("strJson==>" + strJson);
        System.out.println("strArray==>" + strArray);

    }

结果:

从结果中可以看出两种方法都可以把java对象转化为JSON字符串,只是转化后的结构不同


JSON字符串--》》java对象

实例:

 @Test
    public void jsonStrToJava() {
        //定义两种不同格式的字符串
        String objStr = "{\"studentId\": \"001\", \"studentName\": \"张三\"}";
        String arrStr = "[{\"studentId\": \"002\", \"studentName\": \"李四\"},{\"studentId\": \"003\", \"studentName\": \"王武\"}]";

        //1、使用JSONObject
        JSONObject jsonObject = JSONObject.fromObject(objStr);
        Student stu = (Student) jsonObject.toBean(jsonObject, Student.class);

        //2、使用JSONArray
        JSONArray jsonArray = JSONArray.fromObject(arrStr);
        Object obj1 = jsonArray.get(0);
        Object obj2 = jsonArray.get(1);

        JSONObject jsonObject1 = JSONObject.fromObject(obj1);
        JSONObject jsonObject2 = JSONObject.fromObject(obj2);

        Student stu1 = (Student) JSONObject.toBean(jsonObject1, Student.class);
        Student stu2 = (Student) JSONObject.toBean(jsonObject2, Student.class);


        System.out.println("stu===>" + stu);
        System.out.println("stu1===>" + stu1);
        System.out.println("stu2===>" + stu2);
    }

结果:

从上面的代码中可以看出,使用JSONObject可以轻松的把JSON格式的字符串转化为java对象,但是使用JSONArray就没那么容易了,因为它有“[]”符号,所以我们这里在获得了JSONArray的对象之后,取其第一个元素即我们需要的一个student的变形,然后使用JSONObject轻松获得。


list和json字符串的互转

list--》》json字符串

实例:

  @Test
    public void listToJSON() {

        List<Student> list = new ArrayList<>();

        Student stu1 = new Student();
        stu1.setStudentId(1);
        stu1.setStudentName("张三");

        Student stu2 = new Student();
        stu2.setStudentId(2);
        stu2.setStudentName("李四");

        list.add(stu1);
        list.add(stu2);

        //1、使用JSONObject
//        JSONObject jsonObject = JSONObject.fromObject(list);

        //2、使用JSONArray
        JSONArray jsonArray = JSONArray.fromObject(list);

//        System.out.println("jsonObject" + jsonObject);
        System.out.println("jsonArray===>" + jsonArray.toString());

    }

结果:

我把使用JSONObject的方式给注掉了,我们先看注释之前的结果,

Exception in thread "main" net.sf.json.JSONException: 'object' is an array. Use JSONArray instead

告诉我说有一个异常,通过查看源码发现,在使用fromObject方法的时候会先进行参数类型的判断,这里就告诉我们,传入的参数是一个array类型,因为使用的ArrayList,再来看,注释之后的结果,

这样结果是正常的。


json字符串--》》list

实例:

    @Test
    public void jsonToList() {
        String arrStr = "[{\"studentId\": \"002\", \"studentName\": \"李四\"},{\"studentId\": \"003\", \"studentName\": \"王武\"}]";
        JSONArray arr = JSONArray.fromObject(arrStr);
        //转化为list
//        List<Student> list = JSONArray.toList(arr, Student.class);  //过时的方法
//        for (Student student : list) {
//            System.out.println(student);
//        }

        List<Student> list = JSONArray.toList(arr, new Student(), new JsonConfig());   //最新方法
        for (Student student : list) {
            System.out.println(student);
        }


        //转化为数组
        Student[] arrStu = (Student[]) JSONArray.toArray(JSONArray.fromObject(arrStr), Student.class);
        for (Student student : arrStu) {
            System.out.println(student);
        }

    }

结果:

由于字符串的格式为带有“[]”的格式,所以这里选择JSONArray这个对象,它有toArray、toList方法可供使用,前者转化为java中的数组,或者转化为java中的list,由于这里有实体类进行对应,所以在使用时指定了泛型的类型(Student.class),这样就可以得到转化后的对象。


map和json字符串的互转

map--》》json字符串

实例:

    @Test
    public void mapToJSON() {
        List<Student> list = new ArrayList<>();

        Student stu1 = new Student();
        stu1.setStudentId(1);
        stu1.setStudentName("张三");

        Student stu2 = new Student();
        stu2.setStudentId(2);
        stu2.setStudentName("李四");

        list.add(stu1);
        list.add(stu2);

        Map<String, Student> map = new HashMap<String, Student>();
        map.put("first", stu1);
        map.put("second", stu2);

        //1、JSONObject
        JSONObject mapObject = JSONObject.fromObject(map);
        System.out.println("mapObject==>" + mapObject.toString());

        //2、JSONArray
        JSONArray jsonArray = JSONArray.fromObject(map);
        System.out.println("mapArray==>" + jsonArray);

    }

结果:

json字符串--》》map

简单方法

实例:

@Test
    public void json2Map1() {
        Map<String, String> map = new HashMap<>();
        String strObject = "{\"studentId\": \"001\", \"studentName\": \"张三\"}";

        // 将json字符串转换成jsonObject
        JSONObject jsonObject = JSONObject.fromObject(strObject);
        Iterator its = jsonObject.keys();
        // 遍历jsonObject数据,添加到Map对象
        while (its.hasNext()) {
            String key = its.next().toString();
            String value = jsonObject.get(key).toString();
            map.put(key, value);
        }
        // 或者直接将 jsonObject赋值给Map
        // map = jsonObject;
        System.out.println(map);

    }

结果:

json转map通用方法

JSON字符串不能直接转化为map对象,要想取得map中的键对应的值需要别的方式,

处理比较复杂的map用工具类

如:

{
"data": [
           {
            "IR_SRCNAME": "车主之家",
                "IR_SITENAME": "车主之家",
                "IR_AUTHORS": null,
                "IR_URLTITLE": "2017年4月份高尔夫销量11798台, 同比下降20.24%",
                "IR_URLNAME": "http://news.16888.com/a/2017/0521/8172148.html",
                "IR_ABSTRACT": " 2017年4月份高尔夫销量11798台 ",
                "IR_URLTIME": "2017/05/21 23:35:00",
                "IR_HKEYBBSNUM": "18093721078864168420-0",
                "IR_CHANNEL": "新闻_汽车新闻", 
                "COMPANY_RISK_CONN": "汽车之家股份有限公司_财务风险\偿债能力\营运资本_18;",
                "ZFM": "负面"
           }
    	],
        "path": "/cloud/wsu/queryByKeyword!get_by_fullname.action",
                "rstcode": "0000",
                "rstcount": 19476,
                "cmpname": "汽车之家股份有限公司",
                "shortname": "汽车之家",
                "rstmsg": "查询成功"
}

工具类:

import net.sf.json.JSONArray;
import net.sf.json.JSONObject
public class Json2Map {
 
    /**
     * 将json字符串转为Map结构
     * 如果json复杂,结果可能是map嵌套map
     * @param jsonStr 入参,json格式字符串
     * @return 返回一个map
     */
    public static Map<String, Object> json2Map(String jsonStr) {
        Map<String, Object> map = new HashMap<>();
        if(jsonStr != null && !"".equals(jsonStr)){
            //最外层解析
            JSONObject json = JSONObject.fromObject(jsonStr);
            for (Object k : json.keySet()) {
                Object v = json.get(k);
                //如果内层还是数组的话,继续解析
                if (v instanceof JSONArray) {
                    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                    Iterator<JSONObject> it = ((JSONArray) v).iterator();
                    while (it.hasNext()) {
                        JSONObject json2 = it.next();
                        list.add(json2Map(json2.toString()));
                    }
                    map.put(k.toString(), list);
                } else {
                    map.put(k.toString(), v);
                }
            }
            return map;
        }else{
            return null;
        }
    }
}

使用:

    @Test
    public void json2Map() {
        String str = "{\n" +
                "\"data\": [\n" +
                "           {\n" +
                "            \"IR_SRCNAME\": \"车主之家\",\n" +
                "                \"IR_SITENAME\": \"车主之家\",\n" +
                "                \"IR_AUTHORS\": null,\n" +
                "                \"IR_URLTITLE\": \"2017年4月份高尔夫销量11798台, 同比下降20.24%\",\n" +
                "                \"IR_URLNAME\": \"http://news.16888.com/a/2017/0521/8172148.html\",\n" +
                "                \"IR_ABSTRACT\": \" 2017年4月份高尔夫销量11798台 \",\n" +
                "                \"IR_URLTIME\": \"2017/05/21 23:35:00\",\n" +
                "                \"IR_HKEYBBSNUM\": \"18093721078864168420-0\",\n" +
                "                \"IR_CHANNEL\": \"新闻_汽车新闻\", \n" +
                "                \"COMPANY_RISK_CONN\": \"汽车之家股份有限公司_财务风险\\偿债能力\\营运资本_18;\",\n" +
                "                \"ZFM\": \"负面\"\n" +
                "           }\n" +
                "    \t],\n" +
                "        \"path\": \"/cloud/wsu/queryByKeyword!get_by_fullname.action\",\n" +
                "                \"rstcode\": \"0000\",\n" +
                "                \"rstcount\": 19476,\n" +
                "                \"cmpname\": \"汽车之家股份有限公司\",\n" +
                "                \"shortname\": \"汽车之家\",\n" +
                "                \"rstmsg\": \"查询成功\"\n" +
                "}\n";

        Map<String, Object> map = json2Map(str);
        System.out.println(map);
    }

结果:

b.//TODO

c.

4.前台接收json处理的方法

a.

b.

c.

猜你喜欢

转载自blog.csdn.net/a9787206/article/details/81607561