Fastjson:JSON格式的字符串转实体对象

郎家岭伯爵 2023年07月10日 270次浏览

背景

使用 Fastjson 实现把 JSON 格式的字符串转为实体对象。

实现

例如有如下字符串:

{
    "userName": "langjialingbojue",
    "password": "123456",
    "age": 20
}

代码实现:

@GetMapping("t41")
public void test41(){
    String s = "{\n" +
            "    \"userName\": \"langjialingbojue\",\n" +
            "    \"password\": \"123456\",\n" +
            "    \"age\": 20\n" +
            "}";

    UserEntity userEntity = JSON.parseObject(s, UserEntity.class);
    System.out.println(userEntity.getUserName());
    System.out.println(userEntity.getPassword());
    System.out.println(userEntity.getId());
}

输出:

langjialingbojue
123456
null

拓展

把 List 格式的字符串转为 List。

代码:

@GetMapping("t42")
public void test42(){
    String s = "[1,2,3,4,5]";
    List<Integer> list = JSON.parseArray(s, Integer.class);
    System.out.println(list.size());
    System.out.println(list.get(2));
}

输出:

5
3

注:

  • 以上转化均需要字符串在格式上与转换后的数据类型是一致的,否则转化会出错。

总结

使用 Fastjson 可以把字符串转为实体对象、JSONObject、JSONArray、List 等类型的变量,在实际开发中十分好用。

赞助页面示例