引入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version>
</dependency>
将实体类转化为字符串
//实体类Demo
//这里用了几个属性 注意Method 首字母大写
@Data
@ToString
public class Demo {
private String id;
private String userName;
private String Method;
public Demo(String id, String userName, String Method) {
this.id = id;
this.userName = userName;
this.Method = Method;
}
}
public static void main(String[] args) {
Demo demo = new Demo("id", "userName", "Method");
String jsonObj = JSON.toJSONString(demo);
System.out.println(jsonObj);
}
//输出:
//{"id":"id","method":"Method","userName":"userName"}
可看出Method 属性被转化为method 。
解决方法:可在Demo类属性上添加注解 @JSONField
@JSONField(name = "Method")
private String Method;
//测试输出:
//{"Method":"Method","id":"id","userName":"userName"}
将字符串转化为对象
Demo object = JSON.parseObject(jsonObj, Demo.class);