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);

     
     



  • 相关阅读:
    iOS-数据存储的常用方式
    Bullet 学习笔记之 Bullet User Manual
    Bullet 学习笔记之 Bullet User Manual
    Bullet 学习笔记之 Bullet User Manual
    Bullet 学习笔记之 CollisionShape 和 CollisionObject
    Bullet Basic Example 示例
    Bullet 学习笔记
    Gazebo 机器人仿真流程之 World 类(二)
    Gazebo 机器人仿真流程之 WorldPrivate 类
    Gazebo 机器人仿真流程之 World 类
  • 原文地址:https://www.cnblogs.com/yxj808/p/13836485.html
Copyright © 2011-2022 走看看