zoukankan      html  css  js  c++  java
  • JSONObject

    JSONObject只是一种数据结构,可以理解为JSON格式的数据结构(key-value 结构),可以使用put方法给json对象添加元素。JSONObject可以很方便的转换成字符串,也可以很方便的把其他对象转换成JSONObject对象。

    pom:

    1. <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.28</version>
      </dependency>

    1.通过原生生成json数据格式。

    1. JSONObject zhangsan = new JSONObject();
      try {
      //添加
      zhangsan.put("name", "张三");
      zhangsan.put("age", 18.4);
      zhangsan.put("birthday", "1900-20-03");
      zhangsan.put("majar", new String[] {"哈哈","嘿嘿"});
      zhangsan.put("null", null);
      zhangsan.put("house", false);
      System.out.println(zhangsan.toString());
      } catch (JSONException e) {
      e.printStackTrace();
      }

    2.通过hashMap数据结构生成

    1. HashMap<String, Object> zhangsan = new HashMap<>();
      zhangsan.put("name", "张三");
      zhangsan.put("age", 18.4);
      zhangsan.put("birthday", "1900-20-03");
      zhangsan.put("majar", new String[] {"哈哈","嘿嘿"});
      zhangsan.put("null", null);
      zhangsan.put("house", false);
      System.out.println(new JSONObject(zhangsan).toString());

    3.通过实体生成 

      Student student = new Student(); student.setId(1);student.setAge("20"); 

      student.setName("张三"); 

      //生成json格式

      System.out.println(JSON.toJSON(student));

      //对象转成string

      String stuString = JSONObject.toJSONString(student);

    4.JSON字符串转换成JSON对象

    1. String studentString = "{"id":1,"age":2,"name":"zhang"}";
      //JSON字符串转换成JSON对象
      JSONObject jsonObject1 = JSONObject.parseObject(stuString);
      System.out.println(jsonObject1);

    5.list对象转listJson

    1.  ArrayList<Student> studentLsit = new ArrayList<>();
    2. Student student1 = new Student();
    3. student1.setId(1);
    4. student1.setAge("20"); 
    5. student1.setName("asdasdasd");
    6. studentLsit.add(student1);
    7. Student student2 = new Student();
    8. student2.setId(2);
    9. student2.setAge("20");
    10. student2.setName("aaaa:;aaa");
    11. studentLsit.add(student2);
    12. //list转json字符串
    13. String string = JSON.toJSON(studentLsit).toString();
    14. System.out.println(string);
    15. //json字符串转listJson格式
    16. JSONArray jsonArray = JSONObject.parseArray(string);
    17. System.out.println(jsonArray);
     
  • 相关阅读:
    常用的设计模式汇总
    设计模式总结
    C# WinForm文章收集
    SQL Server 2012/2016/2017 新增函数
    SQL Server 日期函数大全
    【BZOJ3622】已经没有什么好害怕的了
    【SDOI2009】Bill的挑战
    【HDU4507】恨7不成妻
    BSOJ 2423 -- 【PA2014】Final Zarowki
    BSOJ 4591 -- 【JLOI2015】城池攻占
  • 原文地址:https://www.cnblogs.com/jinlang/p/13600278.html
Copyright © 2011-2022 走看看