您的位置:首页 > Web前端 > JavaScript

FastJson中@JSONField注解使用

2017-09-13 14:37 507 查看

FastJson中@JSONField注解使用

我们通常使用json格式在服务器之间进行数据传输。

如果json格式数据不符合Java中的标准驼峰式变量定义规则,并且难以理解,这个时候就需要在后台中做二次处理,将数据处理成我们系统中定义的格式。

由于json中的key与bean中的属性不能匹配,通常的转换会出现了部分属性为null的情况。

这种情况,我们可以使用@JSONField。

@JSONField的作用对象:

Field

Setter 和 Getter方法

注:FastJson在进行操作时,是根据getter和setter的方法进行的,并不是依据Field进行。

代码示例:

@JSONField(name = "reason_clear_time", format = "yyyy-MM-dd HH:mm:ss.S")
public void setReasonClearTime(Date reasonClearTime) {
this.reasonClearTime = reasonClearTime;
}

我们的 POJO 属性字段是reasonClearTime,但是我们需要解析的 json 字符串中的 key 是reason_clear_time, 我们通过使用

@JSONField(name = "reason_clear_time", format = "yyyy-MM-dd HH:mm:ss.S")

实现了映射。

另外,format是数据解析的格式。也就是说,reason_clear_time字段的字符串格式是:

2017-09-01 09:47:57.1

转换成 Date 类型。

json字符串解析代码:

public void job() {
String json = PmHitchClient.queryHitchOnline();
List<Hitch> list = null;
try {
list = JSON.parseArray(json, Hitch.class);
logger.info("PmHitchList ===> {}", list);
if (null != list && list.size() > 0) {
for (Hitch h : list) {
setGroupDate(h);
hitchService.save(h);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}

private void setGroupDate(Hitch h) {
String groupDate = "W1 2000-01";
Date catchTime = h.getCatchTime();
String yearMonth = new SimpleDateFormat("yyyy-MM").format(catchTime);
Calendar calendar = Calendar.getInstance();
calendar.setTime(catchTime);
int weekOfMonth = calendar.get(Calendar.WEEK_OF_MONTH);
groupDate = "W" + weekOfMonth + " " + yearMonth;
h.setGroupDate(groupDate);
}

根据某个字段进行增量更新的代码

@Service
public class HitchServiceImpl implements HitchService{
@Autowired
HitchMapper hitchMapper;
@Override
public void save(Hitch record) {
Long hid = record.getHitchId();
if(null!=hid) {
Hitch hitch = hitchMapper.selectByHitchId(hid);
record.setId(hitch.getId());
if (hitch != null) { // 如果该hitch_id 存在记录,更新之
hitchMapper.updateByPrimaryKeySelective(record);
} else {
hitchMapper.insertSelective(record);
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: