项目中遇到后台传给前台的json字符串命名方式不符合java的命名规范 如:
{"exp_value":"exp1","user_age":11,"user_name":"username1"}javabean中是小驼峰命名:
PRivate String userName; private String expValue; private int userAge;关于FastJson属性别名的问题,网上很多文章都指出@JSONField(name = "***")
必须要注解在setter和getter上面;
但是实际测试compile 'com.alibaba:fastjson:1.1.56'
版本的FastJson发现@JSONField注解其实可以直接写到属性名上面,实例如下:
JavaBean
public class JsonTestBean { @JSONField(name = "user_name") private String userName; @JSONField(name = "exp_value") private String expValue; @JSONField(name = "user_age") private int userAge; public String getExpValue() { return expValue; } public void setExpValue(String expValue) { this.expValue = expValue; } public int getUserAge() { return userAge; } public void setUserAge(int userAge) { this.userAge = userAge; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } @Override public String toString() { return "JsonTestBean{" + "expValue='" + expValue + '/'' + ", userName='" + userName + '/'' + ", userAge=" + userAge + '}'; }}Test方法:
@org.junit.Test public void jsonTest() { JsonTestBean jsonTestBean = new JsonTestBean(); jsonTestBean.setUserName("username1"); jsonTestBean.setExpValue("exp1"); jsonTestBean.setUserAge(11); System.out.println("bean->json : " + JsonUtils.toJson(jsonTestBean)); String jsonStr = "{/"exp_value/":/"exp2/",/"user_age/":22,/"user_name/":/"username2/"}"; JsonTestBean toBean = JsonUtils.toBean(jsonStr, JsonTestBean.class); if (toBean != null) { System.out.println("json-> bean : " + toBean.toString()); } }运行结果:
bean->json : {"exp_value":"exp1","user_age":11,"user_name":"username1"}json-> bean : JsonTestBean{expValue='exp2', userName='username2', userAge=22}可以发现@JSONField是可以放在属性上面的
后记:Android SDK更新了,但是build.gradle里面描述没有升级,运行Junit测试始终提示empty test suite 最后升级了gradle里面的版本,错误就解决了
新闻热点
疑难解答