导入依赖
<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>x.x.x</version></dependency>
JSONObject 转 JSON 字符串
Java代码:
JSONObject jsonObject = new JSONObject();jsonObject.put("name", "wjw");jsonObject.put("age", 22);jsonObject.put("sex", "男");jsonObject.put("school", "商职");String jsonStr = JSONObject.toJSONString(jsonObject);System.out.println(jsonStr);
执行结果:
{"school":"商职","sex":"男","name":"wjw","age":22}
JSON 字符串 转 JSONObject 对象
Java代码:
String jsonStr = "{\"school\":\"商职\",\"sex\":\"男\",\"name\":\"wjw\",\"age\":22}";JSONObject jsonObject = JSONObject.parseObject(jsonStr);System.out.println(jsonObject.getString("name"));System.out.println(jsonObject.getInteger("age"));
执行结果:
wjw22
实体类 转 JSONObject对象
创建 Person 对象:
Person person = new Person();person.setName("wjw");person.setAge(22);person.setSex("男");person.setSchool("商职");String personStr = JSONObject.toJSONString(person); // 转换为json字符串System.out.println("personStr:"+personStr);JSONObject personObject = JSONObject.parseObject(personStr); // 转换为json对象System.out.println("personObject:"+personObject);System.out.println("name:"+personObject.getString("name"));
打印结果:
personStr:{"age":22,"name":"wjw","school":"商职","sex":"男"}personObject:{"school":"商职","sex":"男","name":"wjw","age":22}name:wjw
参考地址:
Fastjson 简明教程 | 菜鸟教程
如果觉得《Java通过Fastjson实现JSONObject对象 Json字符串以及Java实体类之间互相转换》对你有帮助,请点赞、收藏,并留下你的观点哦!