fastjson的常用操作

x33g5p2x  于2022-03-31 转载在 其他  
字(2.9k)|赞(0)|评价(0)|浏览(357)

首先引入一个JavaBean类

public class Admin {
    private int id;
    private String name;
    private String password;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

Java对象 转成 JSON字符串

Java对象 -> json字符串JSON.toJSONString(xxx对象)

Admin admin = new Admin(); admin.setId(1); admin.setName("coderzpw"); admin.setPassword("123");
String adminStr = JSON.toJSONString(admin);
System.out.println(adminStr);

输出结果:

{"id":1,"name":"coderzpw","password":"123"}

JSON字符串 转成 Java对象

json字符串 -> Java对象JSON.parseObject(jsonStr, xxx.class)

String jsonStr = "{\"id\":1,\"name\":\"coderzpw\",\"password\":\"123\"}";
Admin admin = JSON.parseObject(jsonStr, Admin.class);
System.out.println(admin);
System.out.println(admin.getClass());

输出结果:

com.hkd.springboottest.hkd.bean.Admin@1e692555
class com.hkd.springboottest.hkd.bean.Admin

复杂JSON对象 的操作

实际上在很多场景下,我们接收的JSON字符串可能是从第三方服务器上获取的,例如ElasticSearch、Prometheus,这些JSON格式是相对复杂的。而如果我们为了接收这些JSON,而去按照对应的JSON格式来自定义一些解析类接收是非常复杂的,而且容易出错。
对于复杂对象的操作,fastjon中为我们提供了 JSONObject:json对象、JSONArray:json数组对象,这两种对象方便我们对复杂JSON数据的解析

Json字符串 -> JSON对象JSONObject.parseObject(jsonStr)
Json数组字符串 -> JSON数组对象JSONObject.parseArray(jsonArrStr)

接下来我以操作这个JSON为例

{
	"部门名称":"研发部",
	"部门成员":[
	{"ID": 1001, "name": "张三", "age": 24},
	{"ID": 1002, "name": "李四", "age": 25},
	{"ID": 1003, "name": "王五", "age": 22}],
	"部门位置":"xx楼21号"
}

目标:张三的年龄
请思考如下代码:

public Object test1(){
    String json = "{\n" +
            "\t\"部门名称\":\"研发部\",\n" +
            "\t\"部门成员\":[\n" +
            "\t{\"ID\": 1001, \"name\": \"张三\", \"age\": 24},\n" +
            "\t{\"ID\": 1002, \"name\": \"李四\", \"age\": 25},\n" +
            "\t{\"ID\": 1003, \"name\": \"王五\", \"age\": 22}],\n" +
            "\t\"部门位置\":\"xx楼21号\"\n" +
            "}";

    // 首先把json字符串转成json对象
    JSONObject totalJsonObject = JSONObject.parseObject(json);
    // 1、 获取到 “成员部门” 这个数组对象
    JSONArray cybm = totalJsonObject.getJSONArray("部门成员");
    // 2、 获取该数组的第一个json对象
    JSONObject jsonObject = cybm.getJSONObject(0);
    // 3、 获取这个对象的“age”
    String age = jsonObject.getString("age");
    return age;
}

操作复杂Json对象的常用方法如下

JSONObject.parseObject(jsonStr) :Json字符串 -> JSON对象
JSONObject.parseArray(jsonArrStr):Json数组字符串 -> JSON数组对象
xxx.getJSONArray("key"):  获取json对象的json数组
xxx.getJSONObject(index): 获取json数组的第index个json对象
xxx.getJSONObject("key"): 获取json对象内层名为"key"的内层json对象
xxx.getString("key"):  获取json对象中key为“key”的字符串

相关文章

微信公众号

最新文章

更多