问题:最近为设备端开发接口,在接口定义阶段,发现一个问题,设备端的参数命名方式是_隔开的,比如first_name,后端的Java命名方式是驼峰标示,比如firstName。怎么把他们对应起来呢?。
办法:采用com.alibaba.fastjson.annotation.JSONField
- 把Java对象中的firstName转化为first_name;
- 把前端的参数first_name映射到Java对象的firstName中。
例子:
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; public class JsonTest { public static void main(String[] args) { Person p = new Person(); p.setFirstName("nihao"); p.setClassId(11); p.setRemart("haha"); // 转化的json字符串,会把firstName对应为first_name String json = JSON.toJSONString(p); System.out.println(json); // 转化的对象,会把first_name对应到firstName Person pp = JSON.parseObject(json, Person.class); System.out.println(pp.getFirstName()); } } class Person { @JSONField(name="first_name") private String firstName; @JSONField(name="class_id") private int classId; private String remart; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public int getClassId() { return classId; } public void setClassId(int classId) { this.classId = classId; } public String getRemart() { return remart; } public void setRemart(String remart) { this.remart = remart; } }