【问题标题】:Best approach to deserializing this API response?反序列化此 API 响应的最佳方法?
【发布时间】:2017-10-27 16:50:19
【问题描述】:

在反序列化 API 响应时,在保存新课程时返回以下内容:

{
    "Error": false,
    "Message": "Course was saved successfully",
    "Result": "1",
    "DataReturn": null
}

我将其反序列化为以下GeneralResultModel.class

package models;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

import models.educationapi.GetCourseDataReturn;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"Error",
"Message",
"Result",
"DataReturn"
})
public class GeneralResultModel implements Serializable
{

@JsonProperty("Error")
private Boolean error;
@JsonProperty("Message")
private String message;
@JsonProperty("Result")
private Object result;
@JsonProperty("DataReturn")
private GetCourseDataReturn dataReturn;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
private final static long serialVersionUID = 4063931322348612559L;

/**
* No args constructor for use in serialization
* 
*/
public GeneralResultModel() {
      }

      /**
      * 
      * @param message
      * @param dataReturn
      * @param result
      * @param error
      */
      public GeneralResultModel(Boolean error, String message, Object result, GetCourseDataReturn dataReturn) {
      super();
      this.error = error;
      this.message = message;
      this.result = result;
      this.dataReturn = dataReturn;
      }

      @JsonProperty("Error")
      public Boolean getError() {
      return error;
      }

      @JsonProperty("Error")
      public void setError(Boolean error) {
      this.error = error;
      }

      @JsonProperty("Message")
      public String getMessage() {
      return message;
      }

      @JsonProperty("Message")
      public void setMessage(String message) {
      this.message = message;
      }

      @JsonProperty("Result")
      public Object getResult() {
      return result;
      }

      @JsonProperty("Result")
      public void setResult(Object result) {
      this.result = result;
      }

      @JsonProperty("DataReturn")
      public Object getDataReturn() {
      return dataReturn;
      }

      @JsonProperty("DataReturn")
      public void setDataReturn(GetCourseDataReturn dataReturn) {
      this.dataReturn = dataReturn;
      }

      @JsonAnyGetter
      public Map<String, Object> getAdditionalProperties() {
      return this.additionalProperties;
      }

      @JsonAnySetter
      public void setAdditionalProperty(String name, Object value) {
      this.additionalProperties.put(name, value);
      }



      @Override
    public String toString() {
        return "[error=" + error + ", message=" + message + ", result=" + result + ", dataReturn="
                + dataReturn +"]";
    }

    @Override
      public boolean equals(Object toCompare) {        

        if (toCompare == this) {
          return false;
        }

        if ((toCompare instanceof GeneralResultModel) == false) {
          return false;
        }

        GeneralResultModel tc = (GeneralResultModel) toCompare;

        if (tc.getResult() == null) {
            tc.setResult("null");
        }

        if (this.getResult() == null) {
            this.setResult("null");
        }

        if (tc.getError() == this.getError() && tc.getDataReturn() == this.getDataReturn() && tc.getMessage().equals(this.getMessage())
            && tc.getResult().equals(this.getResult())) {
              return true;
            }   

        return false;
      }

}

例如,当使用 /getCourse 成功时,我检索到相同的类似响应,只是这一次 DataReturn 不为空,它填充了 inner? 类型为 Course

的对象

我如何稳健地反序列化这样的东西,如果可能的话,我如何在这两种情况下使用相同的 GeneralResultModel?

{
    "Error": false,
    "Message": "",
    "Result": null,
    "DataReturn": [
        {
            "Id": 2,
            "Name": "stack",
            "Description": "overflow#1",
            "ThumbnailFileId": 1,
            "LocationId": 1,


    "PersonId": 0,
        "ProgressPercentage": 0
    },
    {
        "Id": 3,
        "Name": "stack#2",
        "Description": "overflow#2",
        "ThumbnailFileId": 1,
        "LocationId": 1,
        "PersonId": 0,
        "ProgressPercentage": 0
    },
    {
        "Id": 4,
        "Name": "stack#3",
        "Description": "overflow#3",
        "ThumbnailFileId": 1,
        "LocationId": 1,
        "PersonId": 0,
        "ProgressPercentage": 0
    }
]
}

获取 A、获取 B、获取 C 的确切响应是相同的,只是列表会有所不同,所以我如何根据收到的对象类型来满足这一点?

【问题讨论】:

  • 您已将您的类设为通用(GeneralResultModel,其中 T 是 dataReturn 的类型,并使用 GeneralResultModel&lt;List&lt;Course&gt;&gt;
  • 有趣,我对此很陌生,稍后相同的响应将在 DataReturn 值中包含课程对象/模块对象,我最好为每个调用创建一个 GeneralResultModel,例如 GetModulesGeneralResultModel、GetLessonsGeneralResultModel 吗?
  • 这不是我的评论所说的,不。
  • 好的,我将开始阅读泛型,谢谢

标签: java json deserialization web-api-testing


【解决方案1】:

查看 Google 的 Gson。

你要做的就是

Gson gson = new Gson();
GeneralResultModel generalResultModel = gson.fromJson(json, GeneralResultModel.class)

https://github.com/google/gson

【讨论】:

  • 您能否推荐如何最好地构建我的课程,以便如果 DataReturn 是课程列表 ||课程 ||单个类可以处理并映射这些响应的课程内容?目前这一切都让我很困惑
猜你喜欢
  • 2011-07-09
  • 2021-03-04
  • 1970-01-01
  • 1970-01-01
  • 2015-04-20
  • 2012-03-02
  • 2011-09-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多