fastjson版本: 1.2.62
测试效果
测试fastjson转换.png可以看到无论是picUrl1还是PicUrl1, 都能被fastjson转换成对应的picture值.
相关数据
- 建立实体类
@Data
public class SjtsMotorVehicle implements Serializable {
private String picture;
@JSONField(name = "picUrl1")
public void setPicture(String picture) {
this.picture = picture;
}
}
- 封装相关转换工具
/**
* 基于fastjson封装json工具
*
* @author videomonster
* @since 1.0.0
*/
public final class JsonUtil {
/**
* 将json字符串转为指定类型的实例
*
* @param json
* @param cls
* @param <T>
* @return
*/
public static <T> T parse(String json, Class<T> cls) {
return JSON.parseObject(json, cls);
}
}
- 建立单元测试类, 并造两条测试数据
private String sjtsPlateData() {
return "{\n" +
" \"picUrl1\": \"http://52.6.127.134:8088/image/3/3/4b81de96ded14e349705dac07a0de0a8/147/11/16db/1251997095/2180\",\n" +
"}";
}
private String sjtsPlateData1() {
return "{\n" +
" \"PicUrl1\": \"http://52.6.127.134:8188/image/3/3/4b81de96ded14e349705dac07a0de0a8/147/11/16db/1251997095/2180\",\n" +
"}";
}
转换原理
在com.alibaba.fastjson.JSONObject
类中, 我们可以看到invoke
方法, 部分代码如下:
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Class<?>[] parameterTypes = method.getParameterTypes();
if (parameterTypes.length == 1) {
// other code...
String name = null;
JSONField annotation = TypeUtils.getAnnotation(method, JSONField.class);
if (annotation != null) {
if (annotation.name().length() != 0) {
name = annotation.name();
}
}
if (name == null) {
name = method.getName();
if (!name.startsWith("set")) {
throw new JSONException("illegal setter");
}
name = name.substring(3);
if (name.length() == 0) {
throw new JSONException("illegal setter");
}
// 在这里把name属性的首字母转为小写
name = Character.toLowerCase(name.charAt(0)) + name.substring(1);
}
map.put(name, args[0]);
return null;
}
// other code...
}
网友评论