当前位置 博文首页 > 文章内容

    使用JSONObject生成和解析json-json使用详解

    作者:dlxiaoyu01 栏目:前端代码 时间:2021-01-07 10:37:55

    本站于2023年9月4日。收到“大连君*****咨询有限公司”通知
    说我们IIS7站长博客,有一篇博文用了他们的图片。
    要求我们给他们一张图片6000元。要不然法院告我们

    为避免不必要的麻烦,IIS7站长博客,全站内容图片下架、并积极应诉
    博文内容全部不再显示,请需要相关资讯的站长朋友到必应搜索。谢谢!

    另祝:版权碰瓷诈骗团伙,早日弃暗投明。

    相关新闻:借版权之名、行诈骗之实,周某因犯诈骗罪被判处有期徒刑十一年六个月

    叹!百花齐放的时代,渐行渐远!



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

      pom:

      <dependency>

      <groupId>com.alibaba</groupId>

      <artifactId>fastjson</artifactId>

      <version>1.2.28</version>

      </dependency>

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

      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数据结构生成

      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对象

      String studentString = "{\"id\":1,\"age\":2,\"name\":\"zhang\"}";

      //JSON字符串转换成JSON对象

      JSONObject jsonObject1 = JSONObject.parseObject(stuString);

      System.out.println(jsonObject1);

      5.list对象转listJson

      ArrayList<Student> studentLsit = new ArrayList<>();

      Student student1 = new Student();

      student1.setId(1);

      student1.setAge("20");

      student1.setName("asdasdasd");

      studentLsit.add(student1);

      Student student2 = new Student();

      student2.setId(2);

      student2.setAge("20");

      student2.setName("aaaa:;aaa");

      studentLsit.add(student2);

      //list转json字符串

      String string = JSON.toJSON(studentLsit).toString();

      System.out.println(string);

      //json字符串转listJson格式

      JSONArray jsonArray = JSONObject.parseArray(string);

      System.out.println(jsonArray);

      6.string格式的list转成 list

      Object tt="[{id=012345678912, name=wang}, {id=012345678912, name=li }]";

      List<User> subRes = JSON.parseArray(JSON.toJSONString(tt), User.class);

      阿里的json很好用,还有一个谷歌Gson也不错。有兴趣的可以看一看。