【问题标题】:Deserialize separate key-value pair from Json string从 Json 字符串反序列化单独的键值对
【发布时间】:2018-05-25 16:21:38
【问题描述】:

我有课

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

我有一个这样的端点:

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

前端向这个端点发送一个 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() 准备参数时已经完成了这种转换,现在我想将其提取为单独的方法调用。

【问题讨论】:

    标签: spring jackson


    【解决方案1】:
    1. 反序列化为Map&lt;String,String&gt;
    2. 遍历每个条目
    3. 克里特字符串->双对
    4. 发送至Map&lt;String,Double&gt;

    【讨论】:

    • "Crete String->Double pair" Double 仅作为示例,我需要一个一般情况,其中字符串值不应转换为 Double,而是转换为以字符串命名的属性的类型-键。
    • 我在你的例子中没有看到
    猜你喜欢
    • 1970-01-01
    • 2016-12-22
    • 2013-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多