【问题标题】:changing fieldName of Json twice两次更改 Json 的 fieldName
【发布时间】:2019-04-25 00:03:50
【问题描述】:

Spring rest api中是否可以两次更改Json字段名称。我知道这不是很有意义,但我需要这样的东西。

例如,我从远程服务获取的 json 是

{
    total_count : 1;
}

我的模型类是这样的

public class Model
{
     @JsonProperty("total_count")
     int count;
}

从我的休息服务中,我想返回一个模型类的 json,但使用字段“count”而不是“total_count”

{
     count: 1
}

有可能做这样的事情吗?

【问题讨论】:

    标签: json spring-mvc jackson spring-restcontroller


    【解决方案1】:

    尝试类似:

    public class Model {
    
      int count;
    
      @JsonGetter("count")
      public int getCount() {
        return count;
      }
    
      @JsonSetter("total_count")
      public void setCount(int count) {
        this.count = count;
      }
    
    }
    

    【讨论】:

      【解决方案2】:

      如果您不想打扰 pojo 类,那么您可以按照以下解决方案格式化 json 解决方案并发送响应。

      在 JSONObject 上执行以下操作。

      obj.put("count", obj.get("total_count"));
      obj.remove("total_count");
      

      【讨论】:

        猜你喜欢
        • 2021-05-25
        • 1970-01-01
        • 2011-04-24
        • 1970-01-01
        • 1970-01-01
        • 2015-07-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多