zoukankan      html  css  js  c++  java
  • java中 json和bean list map之间的互相转换总结

    JSON字符串和java对象的互转【json-lib】

     

    在开发过程中,经常需要和别的系统交换数据,数据交换的格式有XML、JSON等,JSON作为一个轻量级的数据格式比xml效率要高,XML需要很多的标签,这无疑占据了网络流量,JSON在这方面则做的很好,下面先看下JSON的格式,

    JSON可以有两种格式,一种是对象格式的,另一种是数组对象,

    {"name":"JSON","address":"北京市西城区","age":25}//JSON的对象格式的字符串
    [{"name":"JSON","address":"北京市西城区","age":25}]//数据对象格式


    从上面的两种格式可以看出对象格式和数组对象格式唯一的不同则是在对象格式的基础上加上了[],再来看具体的结构,可以看出都是以键值对的形式出现的,中间以英文状态下的逗号(,)分隔。

    在前端和后端进行数据传输的时候这种格式也是很受欢迎的,后端返回json格式的字符串,前台使用js中的JSON.parse()方法把JSON字符串解析为json对象,然后进行遍历,供前端使用。

    下面进入正题,介绍在JAVA中JSON和java对象之间的互转。

    要想实现JSON和java对象之间的互转,需要借助第三方jar包,这里使用json-lib这个jar包,下载地址为:https://sourceforge.net/projects/json-lib/,json-lib需要commons-beanutils-1.8.0.jar、commons-collections-3.2.1.jar、commons-lang-2.5.jar、commons-logging-1.1.1.jar、ezmorph-1.0.6.jar五个包的支持,可以自行从网上下载,这里不再贴出下载地址。

    json-lib提供了几个类可以完成此功能,例,JSONObject、JSONArray。从类的名字上可以看出JSONObject转化的应该是对象格式的,而JSONArray转化的则应该是数组对象(即,带[]形式)的。

    一、java普通对象和json字符串的互转

      java对象--》》字符串

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

    复制代码
    复制代码
    package com.cn.study.day3;
    
    public class Student {
        //姓名
        private String name;
        //年龄
        private String age;
        //住址
        private String address;
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getAge() {
            return age;
        }
        public void setAge(String age) {
            this.age = age;
        }
        public String getAddress() {
            return address;
        }
        public void setAddress(String address) {
            this.address = address;
        }
        @Override
        public String toString() {
            return "Student [name=" + name + ", age=" + age + ", address="
                    + address + "]";
        }
        
    
    }
    复制代码
    复制代码


     

    上面是我的一个普通的java实体类,看json-lib如何把它转化为字符串形式,

    复制代码
    复制代码
    public static void convertObject() {
            
            Student stu=new Student();
            stu.setName("JSON");
            stu.setAge("23");
            stu.setAddress("北京市西城区");
    
            //1、使用JSONObject
            JSONObject json = JSONObject.fromObject(stu);
            //2、使用JSONArray
            JSONArray array=JSONArray.fromObject(stu);
            
            String strJson=json.toString();
            String strArray=array.toString();
            
            System.out.println("strJson:"+strJson);
            System.out.println("strArray:"+strArray);
        }
    复制代码
    复制代码


     

    我定义了一个Student的实体类,然后分别使用了JSONObject和JSONArray两种方式转化为JSON字符串,下面看打印的结果,

    strJson:{"address":"北京市西城区","age":"23","name":"JSON"}
    strArray:[{"address":"北京市西城区","age":"23","name":"JSON"}]

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

      JSON字符串--》》java对象

    上面说明了如何把java对象转化为JSON字符串,下面看如何把JSON字符串格式转化为java对象,

    首先需要定义两种不同格式的字符串,需要使用对双引号进行转义,

    复制代码
    复制代码
    public static void jsonStrToJava(){
            //定义两种不同格式的字符串
            String objectStr="{"name":"JSON","age":"24","address":"北京市西城区"}";
            String arrayStr="[{"name":"JSON","age":"24","address":"北京市西城区"}]";
        
            //1、使用JSONObject
            JSONObject jsonObject=JSONObject.fromObject(objectStr);
            Student stu=(Student)JSONObject.toBean(jsonObject, Student.class);
            
            //2、使用JSONArray
            JSONArray jsonArray=JSONArray.fromObject(arrayStr);
            //获得jsonArray的第一个元素
            Object o=jsonArray.get(0);
            JSONObject jsonObject2=JSONObject.fromObject(o);
            Student stu2=(Student)JSONObject.toBean(jsonObject2, Student.class);
            System.out.println("stu:"+stu);
            System.out.println("stu2:"+stu2);
            
        }
    复制代码
    复制代码

    打印结果为:

    stu:Student [name=JSON, age=24, address=北京市西城区]
    stu2:Student [name=JSON, age=24, address=北京市西城区]

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

    二、list和json字符串的互转

    list--》》json字符串

    复制代码
    复制代码
    public static void listToJSON(){
            Student stu=new Student();
            stu.setName("JSON");
            stu.setAge("23");
            stu.setAddress("北京市海淀区");
            List<Student> lists=new ArrayList<Student>();
            lists.add(stu);
            //1、使用JSONObject
            //JSONObject listObject=JSONObject.fromObject(lists);
            //2、使用JSONArray
            JSONArray listArray=JSONArray.fromObject(lists);
            
            //System.out.println("listObject:"+listObject.toString());
            System.out.println("listArray:"+listArray.toString());
            
        }
    复制代码
    复制代码

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

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

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

    listArray:[{"address":"北京市海淀区","age":"23","name":"JSON"}]

    这样结果是正常的。
    json字符串--》》list

    从上面的例子可以看出list的对象只能转化为数组对象的格式,那么我们看下面的字符串到list的转化,

    复制代码
    复制代码
    public static void jsonToList(){
            String arrayStr="[{"name":"JSON","age":"24","address":"北京市西城区"}]";
            //转化为list
                    List<Student> list2=(List<Student>)JSONArray.toList(JSONArray.fromObject(arrayStr), Student.class);
                    
                    for (Student stu : list2) {
                        System.out.println(stu);
                    }
                    //转化为数组
                    Student[] ss =(Student[])JSONArray.toArray(JSONArray.fromObject(arrayStr),Student.class);
                    for (Student student : ss) {
                        System.out.println(student);
                    }
            
            
        }
    复制代码
    复制代码

    打印结果,

    Student [name=JSON, age=24, address=北京市西城区]
    Student [name=JSON, age=24, address=北京市西城区]

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

    三、map和json字符串的互转

    map--》》json字符串

    复制代码
    复制代码
    public static void mapToJSON(){
            Student stu=new Student();
            stu.setName("JSON");
            stu.setAge("23");
            stu.setAddress("中国上海");
            Map<String,Student> map=new HashMap<String,Student>();
            map.put("first", stu);
            
            //1、JSONObject
            JSONObject mapObject=JSONObject.fromObject(map);
            System.out.println("mapObject"+mapObject.toString());
            
            //2、JSONArray
            JSONArray mapArray=JSONArray.fromObject(map);
            System.out.println("mapArray:"+mapArray.toString());
        }
    复制代码
    复制代码

    打印结果,

    mapObject{"first":{"address":"中国上海","age":"23","name":"JSON"}}
    mapArray:[{"first":{"address":"中国上海","age":"23","name":"JSON"}}]

    上面打印了两种形式。

    json字符串--》》map

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

    复制代码
    复制代码
    public static void jsonToMap(){
            String strObject="{"first":{"address":"中国上海","age":"23","name":"JSON"}}";
            
            //JSONObject
            JSONObject jsonObject=JSONObject.fromObject(strObject);
            Map map=new HashMap();
            map.put("first", Student.class);
    
    //使用了toBean方法,需要三个参数
    MyBean my=(MyBean)JSONObject.toBean(jsonObject, MyBean.class, map); System.out.println(my.getFirst()); }
    复制代码
    复制代码

    打印结果,

    Student [name=JSON, age=23, address=中国上海]

    下面是MyBean的代码,

    复制代码
    复制代码
    package com.cn.study.day4;
    
    import java.util.Map;
    
    import com.cn.study.day3.Student;
    
    public class MyBean {
        
        private Student first;
    
        public Student getFirst() {
            return first;
        }
    
        public void setFirst(Student first) {
            this.first = first;
        }
    
        
    
    }
    复制代码
    复制代码

    使用toBean()方法是传入了三个参数,第一个是JSONObject对象,第二个是MyBean.class,第三个是一个Map对象。通过MyBean可以知道此类中要有一个first的属性,且其类型为Student,要和map中的键和值类型对应,即,first对应键 first类型对应值的类型。

    、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、

    使用spring框架中 jackson jar包中的 ObjectMapper()类json和bean list map之间的互相转换总结

    (1)把对象集合转换成json格式

    自己做了一java对象转换为json对象的小示例:JacksonTest.java

    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    import org.codehaus.jackson.map.ObjectMapper;
    
    public class JacksonTest {
        public static void main(String[] args) throws Exception {
            ObjectMapper objectMapper = new ObjectMapper();
            List<Person> persons = new ArrayList<Person>();
            Integer[] arrays = new Integer[2];
            Person person = null;
            for (int i = 0; i < 2; i++) {
                person = new Person("test" + i, "pwd" + i, "phone" + i,
                        "tencent@QQ.com" + i, "男", "23");
                persons.add(person);
                arrays[i] = i;
            }
            Map<String, String> tipMap = new HashMap<String, String>();
            tipMap.put("valueName", "10");
            tipMap.put("valueName2", "3");
            tipMap.put("valueName3", "5");
            tipMap.put("valueName4", "8");
            Map<String, Object> map2Json = new HashMap<String, Object>();
            // 加入list对象
            map2Json.put("personKey", persons);
            // 加入map对象
            map2Json.put("mapKey", tipMap);
            // 加入数组对象
            map2Json.put("idKey", arrays);      
            //转化为json字符串
            String json = objectMapper.writeValueAsString(map2Json);
            System.out.println(json);
        }
    }
    

    Person.java

    import java.io.Serializable;
    
    public class Person implements Serializable{
        private String userName;
        private String password;
        private String phone;
        private String email;
        private String sex;
        private String age;
    
        public Person(){}
    
        public Person(String userName, String password, String phone, String email,
                String sex, String age) {
            super();
            this.userName = userName;
            this.password = password;
            this.phone = phone;
            this.email = email;
            this.sex = sex;
            this.age = age;
        }
        。。。省略get()和set()方法
    }

    运行结果:

    {
        "personKey": [{
            "userName": "test0",
            "password": "pwd0",
            "phone": "phone0",
            "email": "tencent@QQ.com0",
            "sex": "男",
            "age": "23"
        },
        {
            "userName": "test1",
            "password": "pwd1",
            "phone": "phone1",
            "email": "tencent@QQ.com1",
            "sex": "男",
            "age": "23"
        }],
        "mapKey": {
            "valueName": "10",
            "valueName2": "3",
            "valueName3": "5",
            "valueName4": "8"
        },
        "idKey": [0,1]
    }

    Jackson jar包的下载地址http://jackson.codehaus.org/1.7.6/jackson-all-1.7.6.jar

    如果是首次使用该jar包还可以阅读官方的示例:http://wiki.fasterxml.com/JacksonInFiveMinutes

    github:https://github.com/FasterXML/jackson-core 
    当然该jar包还有许多其他的很多强大的api,大家可以自行学习

    (2)

    把json转换成list maop等对象

    1. public class JacksonTest {  
    2.  private static JsonGenerator jsonGenerator = null;  
    3.  private static ObjectMapper objectMapper = null;  
    4.  private static User user = null;  
    5.   
    6.  public static void writeEntity2Json() throws IOException {  
    7.   System.out.println("使用JsonGenerator转化实体为json串-------------");  
    8.   // writeObject可以转换java对象,eg:JavaBean/Map/List/Array等  
    9.   jsonGenerator.writeObject(user);  
    10.   System.out.println();  
    11.   System.out.println("使用ObjectMapper-----------");  
    12.   // writeValue具有和writeObject相同的功能  
    13.   objectMapper.writeValue(System.out, user);  
    14.  }  
    15.   
    16.  public static void writeList2Json() throws IOException {  
    17.   List<User> userList = new ArrayList<User>();  
    18.   userList.add(user);  
    19.   User u = new User();  
    20.   u.setUid(10);  
    21.   u.setUname("archie");  
    22.   u.setUpwd("123");  
    23.   userList.add(u);  
    24.   objectMapper.writeValue(System.out, userList);  
    25.  }  
    26.   
    27.  public static void writeMap2Json() {  
    28.   try {  
    29.    Map<String, Object> map = new HashMap<String, Object>();  
    30.    User u = new User();  
    31.    u.setUid(10);  
    32.    u.setUname("archie");  
    33.    u.setUpwd("123");  
    34.    map.put("uid", u.getUid());  
    35.    map.put("uname", u.getUname());  
    36.    map.put("upwd", u.getUpwd());  
    37.    System.out.println("jsonGenerator");  
    38.    jsonGenerator.writeObject(map);  
    39.    objectMapper.writeValue(System.out, map);  
    40.   } catch (IOException e) {  
    41.    e.printStackTrace();  
    42.   }  
    43.  }  
    44.   
    45.  public static void writeOthersJSON() {  
    46.   try {  
    47.    String[] arr = { "a", "b", "c" };  
    48.    System.out.println("jsonGenerator");  
    49.    String str = "hello world jackson!";  
    50.    // byte  
    51.    jsonGenerator.writeBinary(str.getBytes());  
    52.    // boolean  
    53.    jsonGenerator.writeBoolean(true);  
    54.    // null  
    55.    jsonGenerator.writeNull();  
    56.    // float  
    57.    jsonGenerator.writeNumber(2.2f);  
    58.    // char  
    59.    jsonGenerator.writeRaw("c");  
    60.    // String  
    61.    jsonGenerator.writeRaw(str, 5, 10);  
    62.    // String  
    63.    jsonGenerator.writeRawValue(str, 5, 5);  
    64.    // String  
    65.    jsonGenerator.writeString(str);  
    66.    jsonGenerator.writeTree(JsonNodeFactory.instance.POJONode(str));  
    67.    System.out.println();  
    68.    // Object  
    69.    jsonGenerator.writeStartObject();// {  
    70.    jsonGenerator.writeObjectFieldStart("user");// user:  
    71.    jsonGenerator.writeStringField("name", "jackson");// name:jackson  
    72.    jsonGenerator.writeBooleanField("sex", true);// sex:true  
    73.    jsonGenerator.writeNumberField("age", 22);// age:22  
    74.    jsonGenerator.writeEndObject();  
    75.    jsonGenerator.writeArrayFieldStart("infos");// infos:[  
    76.    jsonGenerator.writeNumber(22);// 22  
    77.    jsonGenerator.writeString("this is array");// this is array  
    78.    jsonGenerator.writeEndArray();// ]  
    79.    jsonGenerator.writeEndObject();// }  
    80.    User u = new User();  
    81.    user.setUid(5);  
    82.    user.setUname("tom");  
    83.    user.setUpwd("123");  
    84.    user.setNumber(3.44);  
    85.    // complex Object  
    86.    jsonGenerator.writeStartObject();// {  
    87.    jsonGenerator.writeObjectField("uid", u);// user:{bean}  
    88.    jsonGenerator.writeObjectField("infos", arr);// infos:[array]  
    89.    jsonGenerator.writeEndObject();// }  
    90.   } catch (Exception e) {  
    91.    e.printStackTrace();  
    92.   }  
    93.  }  
    94.   
    95.  /** 
    96.   * JSON字符串转换为对象 
    97.   */  
    98.  public static void readJson2Entity() {  
    99.   String json = "{"uid":5,"uname":"tom","number":3.44,"upwd":"123"}";  
    100.   try {  
    101.    User acc = objectMapper.readValue(json, User.class);  
    102.    System.out.println(acc.getUid());  
    103.    System.out.println(acc);  
    104.   } catch (JsonParseException e) {  
    105.    e.printStackTrace();  
    106.   } catch (JsonMappingException e) {  
    107.    e.printStackTrace();  
    108.   } catch (IOException e) {  
    109.    e.printStackTrace();  
    110.   }  
    111.  }  
    112.   
    113.  /** 
    114.   * JSON转换为List对象 
    115.   */  
    116.  public static void readJson2List() {  
    117.   String json = "[{"uid":1,"uname":"www","number":234,"upwd":"456"},"  
    118.     + "{"uid":5,"uname":"tom","number":3.44,"upwd":"123"}]";  
    119.   try {  
    120.    List<LinkedHashMap<String, Object>> list = objectMapper.readValue(  
    121.      json, List.class);  
    122.    System.out.println(list.size());  
    123.    for (int i = 0; i < list.size(); i++) {  
    124.     Map<String, Object> map = list.get(i);  
    125.     Set<String> set = map.keySet();  
    126.     for (Iterator<String> it = set.iterator(); it.hasNext();) {  
    127.      String key = it.next();  
    128.      System.out.println(key + ":" + map.get(key));  
    129.     }  
    130.    }  
    131.   } catch (JsonParseException e) {  
    132.    e.printStackTrace();  
    133.   } catch (JsonMappingException e) {  
    134.    e.printStackTrace();  
    135.   } catch (IOException e) {  
    136.    e.printStackTrace();  
    137.   }  
    138.  }  
    139.   
    140.  /** 
    141.   * JSON转换为数组对象 
    142.   */  
    143.  public static void readJson2Array() {  
    144.   String json = "[{"uid":1,"uname":"www","number":234,"upwd":"456"},"  
    145.     + "{"uid":2,"uname":"sdfsdf","number":4745,"upwd":"23456"}]";  
    146.   try {  
    147.    User[] arr = objectMapper.readValue(json, User[].class);  
    148.    System.out.println(arr.length);  
    149.    for (int i = 0; i < arr.length; i++) {  
    150.     System.out.println(arr[i]);  
    151.    }  
    152.   } catch (JsonParseException e) {  
    153.    e.printStackTrace();  
    154.   } catch (JsonMappingException e) {  
    155.    e.printStackTrace();  
    156.   } catch (IOException e) {  
    157.    e.printStackTrace();  
    158.   }  
    159.  }  
    160.   
    161.  /** 
    162.   * JSON转换为Map对象 
    163.   */  
    164.  public static void readJson2Map() {  
    165.   String json = "{"success":true,"A":{"address": "address2","name":"haha2","id":2,"email":"email2"},"+    
    166.   ""B":{"address":"address","name":"haha","id":1,"email":"email"}}";  
    167.   try {  
    168.    Map<String, Map<String, Object>> maps = objectMapper.readValue(json, Map.class);  
    169.    System.out.println(maps.size());  
    170.    Set<String> key = maps.keySet();  
    171.    Iterator<String> iter = key.iterator();  
    172.    while (iter.hasNext()) {  
    173.     String field = iter.next();  
    174.     System.out.println(field + ":" + maps.get(field));  
    175.    }  
    176.   } catch (JsonParseException e) {  
    177.    e.printStackTrace();  
    178.   } catch (JsonMappingException e) {  
    179.    e.printStackTrace();  
    180.   } catch (IOException e) {  
    181.    e.printStackTrace();  
    182.   }  
    183.  }  
    184.   
    185.  public static void main(String[] args) {  
    186.   user = new User();  
    187.   user.setUid(5);  
    188.   user.setUname("tom");  
    189.   user.setUpwd("123");  
    190.   user.setNumber(3.44);  
    191.   objectMapper = new ObjectMapper();  
    192.   try {  
    193.    //jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(System.out, JsonEncoding.UTF8);  
    194.    // writeEntity2Json();  
    195.    // writeMap2Json();  
    196.    // writeList2Json();  
    197.    // writeOthersJSON();  
    198.    // readJson2Entity();  
    199.    // readJson2List();  
    200. //   readJson2Array();  
    201.    readJson2Map();  
    202.   } catch (Exception e) {  
    203.    e.printStackTrace();  
    204.   }  
    205.  }  
    206. }  
  • 相关阅读:
    服务器出现大量的127.0.0.1:3306 TIME_WAIT连接 解决方法 [转载]
    phpize安装php扩展CURL
    linux位数查看
    Linux下Sublime Text 3的安装
    ECstore后台报表显示空白问题解决办法
    centos 上安装phpstorm
    Nginx禁止目录执行php文件权限
    vue 动画
    vue的路由
    组件的传值 组件之间的通讯
  • 原文地址:https://www.cnblogs.com/ConfidentLiu/p/7571278.html
Copyright © 2011-2022 走看看