JSON.parseObject 实例
json
适用于现代 C++ 的 JSON。
项目地址:https://gitcode.com/gh_mirrors/js/json
免费下载资源
·
前言
实践一下 JSON 类的 public static final <T> T parseObject(String text, Class<T> clazz)
方法,看一下效果,基于 fastjson-1.2.54.jar 版本
Student 类
package com.yuanhao.test;
public class Student {
public String name;
private String sex;
public int age;
public boolean isGraduate;
public String home;
@Override
public String toString() {
return "Student {" + "name:'" + name + "',"
+ "sex:'" + sex + "',"
+ "age:" + age +","
+ "isGraduate:'" + isGraduate + "',"
+ "home:'" + home + "'}";
}
}
Mytest 类
package com.yuanhao.test;
import com.alibaba.fastjson.JSON;
public class Mytest {
public static void main(String[] args) {
String jsonStr = "{\"name\":\"ZhangSan\",\"age\":22,\"sex\":\"male\",\"isGraduate\":\"true\",\"isBad\":false}";
System.out.println("json string: " + jsonStr);
Student stu = JSON.parseObject(jsonStr, Student.class);
System.out.println("student toString: " + stu.toString());
String stuStr = JSON.toJSONString(stu);
System.out.println("JSON 串: " + stuStr);
}
}
结果
json string: {"name":"ZhangSan","age":22,"sex":"male","isGraduate":"true","isBad":false}
student toString: Student {name:'ZhangSan',sex:'null',age:22,isGraduate:'true',home:'null'}
JSON 串: {"age":22,"isGraduate":true,"name":"ZhangSan"}
总结
- parseObject 时会根据定义的类(Student)的成员名称进行解析
- 定义类(Student)的成员需定义为 public 类型,否则解析不出来,如 “sex” 字段
- json string 中没有的字段(Student 有此成员),如 “home” 字段,解析结果为 null、0、false(对应 String、int、boolean 类型)等
GitHub 加速计划 / js / json
41.72 K
6.61 K
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:1 个月前 )
960b763e
4 个月前
8c391e04
7 个月前
更多推荐
已为社区贡献1条内容
所有评论(0)