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

     
     



  • 相关阅读:
    Rock the Tech Interview
    k-d Tree in TripAdvisor
    Randomized QuickSelect
    Kth Smallest Element in Unsorted Array
    Quick Sort
    LRU Cache 解答
    Implement Queue using Stacks 解答
    Implement Stack using Queues 解答
    ListNode Review ReverseListNode
    BackTracking
  • 原文地址:https://www.cnblogs.com/yxj808/p/13836485.html
Copyright © 2020-2023  润新知