Java Bean对象、Json字符串之间互转中 驼峰命名与下划线命名之间互转

时间:2025-02-16 11:23:26
package com.wyp.sms; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.annotation.JSONField; import lombok.Data; /** * 驼峰命名 属性名称 转 json后 属性名称显示为下划线命名 * 属性名称 为 aBcD 的对象 转成 json 后 {"a_bc_d_e_f":"aaa"} * * {"a_bc_d_e_f":"aaa"} 字符串 转 属性名称 为 aBcD 的对象 */ public class ObjToJsonStr { public static void main(String[] args) { // Bean对象转Json字符串 TestJSONObj testJSON = new TestJSONObj(); testJSON.setABcD("aaa"); String jsonStr = JSON.toJSONString(testJSON); System.out.println("jsonStr = " + jsonStr); // 输出:{"a_bc_d_e_f":"aaa"} // Json字符串转Bean对象 String str = "{\"a_bc_d_e_f\":\"aaa\"}"; TestJSONObj obj = JSONObject.parseObject(str, TestJSONObj.class); System.out.println(obj.getABcD()); // 输出:aaa } /** * 要序列化的类 */ @Data public static class TestJSONObj { @JSONField(name = "a_bc_d_e_f") private String aBcD; } }