zoukankan      html  css  js  c++  java
  • bean与json之间转换

    1.json依赖
    <dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20160810</version>
    </dependency>


    Student student = new Student();
    student.setId(1);
    student.setName("zhangsan");

    /** 把java 对象转换成 json 数据
    * 1.转成json对象
    * 2.转成json字符串
    */
    JSONObject jsonObject = JSONObject.fromObject(student);
    String string = jsonObject.toString();
    System.out.println("json数据"+string);
    /**
    * json 对象 转 java 对象
    */
    JSONObject json = new JSONObject();
    json.put("id",2);
    json.put("name","lisi");
    Student bean = (Student) JSONObject.toBean(json, Student.class);
    System.out.println("bean:id"+bean.getId()+"name"+bean.getName());
    /**
    * json对象转成指定的list
    */
    JSONObject json2 = new JSONObject();
    Student student2 = new Student();
    student2.setId(3);
    student2.setName("wangwu");
    Student student3 = new Student();
    student3.setId(4);
    student3.setName("wangxiaoming");
    List<Student> list = new ArrayList();
    list.add(student2);
    list.add(student3);
    json2.put("students",list);
    JSONArray students = (JSONArray)json2.get("students");
    List<Student> list2 = JSONArray.toList(students, new Student(), new JsonConfig());
    System.out.println("json转list:"+list2.get(1).getName());
    //list 转json数据

    JSONArray array = JSONArray.fromObject(list);
    System.out.println("list转json:"+array);

    2.<!--json--> fastjson
    <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.47</version>
    </dependency>
    1. JsonToBean JSON.parseObject(String jsonData, Student.class)
    Student student= Json.parseObject(data, Student.class);
    2.
    BeanToJson JSON.toJSONString(object)
    String json=JSON.toJSONString(student);
    3.
    JsonToList JSON.parseArray(String jsonData, Student.class)
    List<Student> list= JSON.parseArray(data, Student.class);

     
     



  • 相关阅读:
    无名信号量在多线程间的同步
    ftok函数例子
    strerror和perror函数详解
    lockf函数的使用
    背包问题-2动态规划【正解】
    递归思想即背包问题
    生产者消费者问题(基于线程和无名信号量)
    eclipse 安装python后pydev不出现
    Eclipse+pydev解决中文显示和注释问题的方法大全
    MyEclipse10配置PyDev进行Python开发
  • 原文地址:https://www.cnblogs.com/yxj808/p/13836485.html
Copyright © 2011-2022 走看看