从Json字符串反序列化单独的键值对

时间:2018-05-25 16:21:39

标签: spring jackson

我有一个班级

Entity implements org.joda.beans.Bean {
    String name;
    double weight;
    ....
}

我有一个这样的端点:

@RequestMapping(value = "CREATE", method = POST)
public void createEntity(@RequestBody Entity entity) {
    logic.createEntity(entity);
}

Frontend将Json字符串发送到此端点:

{"name": "Bob", "weight":"99.7"}

现在我想要另一个端点来更新实体。 它接受json字符串,其中只设置了部分属性:

{"weight":"99.8"}

它的签名可能是这样的:

@RequestMapping(value = "UPDATE", method = POST)
public void updateCompany(@RequestBody Map<String, String> update1) {
    Map<String, Object> update2 = deserialize(Entity.class,update1);
    logic.updateEntity(update2);
}

问题是,如何实现方法deserialize,它接受​​一对字符串[“weight”,“99.8”]并将其转换为String-Object对:[“weight”,Double.valueOf( “99.8”)]因为它知道,类Entity中声明的权重类型是双倍的。这种转换在准备方法createEntity()的参数时已经完成,现在我想将其作为单独的方法调用提取。

1 个答案:

答案 0 :(得分:-1)

  1. 反序列化为Map<String,String>
  2. 对每个条目进行迭代
  3. Crete String-&gt; Double pair
  4. 加入Map<String,Double>