博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
alibaba.fastjson.JSONObject 解析
阅读量:4475 次
发布时间:2019-06-08

本文共 1600 字,大约阅读时间需要 5 分钟。

public class JsonDemo {

public static void main(String[] args) {

//1.json字符串转换为对象

  String jsonString="{'name':'42313123','id':'2345','age':12}";

  JSONObject jsonObject = JSONObject.parseObject(jsonString);
  String id = jsonObject.getString("id");
  System.out.println(id);

//2. JSONObject转化成自定义类对象

  PeoplePo peoplePo1 = JSONObject.parseObject(jsonString, PeoplePo.class);

  System.out.println(peoplePo1);

 

//3. JSONObject转化成Map集合

  Map map = JSONObject.parseObject(jsonString, Map.class);

  System.out.println(map);

 

//4. 自定义对象转化成json格式的字符串

  PeoplePo peoplePo = new PeoplePo();

  peoplePo.setId("1");
  peoplePo.setAge(11);
  peoplePo.setName("LH");
  String peopleJson = JSON.toJSONString(peoplePo);
  System.out.println(peopleJson);

 

//5. String类型转化成JSONObject;

  String str = "{\"result\":\"success\",\"message\":\"成功!\"}";

  JSONObject jsonObject1 = JSONObject.parseObject(str);
  System.out.println(jsonObject1);

 

//6. JSONObject转化成JSONArray的两种方式

  String str1 = "{\"result\":\"success\",\"message\":\"成功!\",\"data\":[{\"name\":\"Tom\",\"age\":\"20\"}]}";

  JSONObject jsonToArray = JSONObject.parseObject(str1);
  //方式一
  JSONArray data = jsonToArray.getJSONArray("data");
  System.out.println(data);
  //方式二
  JSONArray jsonArray = JSONArray.parseArray(jsonToArray.getString("data"));
  System.out.println(jsonArray);

 

//7. jsonArray转化成JSONObject并取出其中的元素数据

  JSONObject o = (JSONObject) jsonArray.get(0);

  String name = o.getString("name");
  System.out.println(o);
  System.out.println(name);
  System.out.println(jsonArray.toString());

      }

}

 

转载于:https://www.cnblogs.com/min-yu/p/11412643.html

你可能感兴趣的文章
Redis与Python交互
查看>>
Maximum-SubsequenceSum
查看>>
常用的一些shell变量
查看>>
Android无法删除项目+导入项目报错
查看>>
poj 2349(最小生成树应用)
查看>>
python接口自动化测试二十五:执行所有用例,并生成HTML测试报告
查看>>
c# 指定的存储区提供程序在配置中找不到,或者无效
查看>>
最简陋的python数据
查看>>
第一堂java web课
查看>>
操作系统简介
查看>>
第1周小组博客作业--1703班06组
查看>>
vue项目中icon图标的完美引入
查看>>
C语言指针
查看>>
Java的安装
查看>>
0920 JSON数据 蓝懿
查看>>
Azure Cosmos DB 使用费用参考
查看>>
【嵌入式开发】写入开发板Linux系统-模型S3C6410
查看>>
C# 子线程与主线程通讯方法一
查看>>
006——修改tomacat的编码
查看>>
《C程序设计语言》笔记 (八) UNIX系统接口
查看>>