栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java-JSON转换

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java-JSON转换

FastJSON

FastJson是一个Java库,可以将Java对象转换为JSON格式,当然它也可以将JSON字符串转换为Java对象

提供了toJSonString()和parseObject()方法来将Java对象与JSON相互转换,调用toJSonString()方法即可将对象转换成JSON字符串
parseObject方法则反过来将JSON字符串转换成对象

使用步骤
    添加依赖
    	
    	
    	    com.alibaba
    	    fastjson
    	    1.2.78
    	
    
    测试
实体类:
	public class Users {
    private int uid; // 用户实体的主键属性
    private String uname; // 用户账号
    private String upassword; // 用户密码
    private String uemail; // 用户邮箱 用于激活使用
    private String usex; // 用户性别
    private int ustatus; // 用户激活状态 0 未激活 1 激活
    private String ucode; // 邮件激活码
    private int urole; // 用户 0 管理员 1
    // JavaBean...
    }

单元测试:
	@Test
    public void testFastJson() {
        Users users = new Users(2022, "coderitl", "coderitl", "123xxx@qq.com", "男", 1, "2022", 2);
        // 将实体类转换为 json 格式
        String strToJsonUser = JSON.toJSONString(users);
        System.out.println(strToJsonUser);
    }

输出
Jackson-JSON操作

Jackson是一个能否将Java对象序列化为JSON字符串,也能够将JSON字符串反序列化为Java对象的框架

通过方法readvalue和writevalue实现

使用步骤
    添加依赖或者下载对应jar文件

    com.fasterxml.jackson.core
    jackson-annotations
    2.13.0




    com.fasterxml.jackson.core
    jackson-core
    2.13.0




    com.fasterxml.jackson.core
    jackson-databind
    2.13.0


    使用
@Test
  public void testJackSon() throws JsonProcessingException {
      ObjectMapper mapper = new ObjectMapper();
      Users users = new Users(2022, "coderitl", "coderitl", "123xxx@qq.com", "男", 1, "2022", 2);
      String s = mapper.writevalueAsString("testJackSon: "+users);
      System.out.println(s);
  }

JSON格式字符串转换为实体类

@Test
    public void testJackSon() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        // JSON 字符串
        String message = "{n" +
                "t"uid": 2022,n" +
                "t"uname": "coderitl",n" +
                "t"upassword": "coderitl",n" +
                "t"uemail": "123xxx@qq.com",n" +
                "t"usex": "男",n" +
                "t"ustatus": 1,n" +
                "t"ucode": "2022",n" +
                "t"urole": 2n" +
                "}";
        Users users = mapper.readValue(message, Users.class);
        System.out.println(users);
    }
浏览器处理JSON

测试

// 对象
const obj = {name: "coder-itl", age: 20, address: "testJson"};
console.log(typeof (obj)); // object
// 将浏览器对象转换为字符串方法
let res = JSON.stringify(obj);
console.log(typeof (res)); // String
// 将字符串转换为 Object
res = JSON.parse(res);
console.log(typeof (res)); // object
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/731664.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号