将restful响应反序列化为自定义类的问题 [英] Issues with deserialization of restful responses into custom class

查看:76
本文介绍了将restful响应反序列化为自定义类的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在尝试使用泛型开发一些代码,我的想法如下:


我们有大量的API测试,每个测试需要一些非常长的时间复杂的电话,因为他们很难记住,我正在考虑用课程来做这件事。您使用Request和Response创建两个类,并填充所需的属性
并将其序列化为XML,JSON或FORM,并在Response类中填充结果。


要制作发生这种情况我有两个抽象类 - RESTfulRequest和RESTfulResponse。


这两个类将被任何将用于RESTful调用的类继承。

公共抽象类RESTFulRequest 
{

#region Public Fields

public string Url {get;组;
public ContentType ContentType {get;组; }
public List< KeyValue> CustomHeaders {get;组; }

#endregion

#region Public Constuctors

public RESTFulRequest()
{
this.CustomHeaders = new List< ; KEYVALUE>();
}

#endregion

}

公共类RESTFulResponseInternal
{
#region Public Constructors

///< summary>
///使用指定的状态代码和内容初始化类。
///< / summary>
///< param name =" statusCode"> http状态代码。< / param>
///< param name =" isSuccessStatusCode">一个布尔值,指示http响应是否成功。< / param>
///< param name =" content"> http响应内容。< / param>
public RESTFulResponseInternal(HttpStatusCode statusCode,bool isSuccessStatusCode,string content)
{
StatusCode = statusCode;
IsSuccessStatusCode = isSuccessStatusCode;
内容=内容;
}

#endregion

#region公共属性

///< summary>
///获取http状态代码。
///< / summary>
public HttpStatusCode StatusCode {get;私人集; }

///< summary>
///获取一个值,指示http响应是否成功。
///< / summary>
public bool IsSuccessStatusCode {get;私人集; }

///< summary>
///获取http响应内容。
///< / summary>
public string Content {get;私人集; }

#endregion
}




下一页我为继承Request类的每个类都有一个扩展方法


 public static TResult POST< TResult> ;(此RESTFulRequest obj,字符串accessToken ="")
其中TResult:RESTFulResponse,new()
{
if(obj == null)return default(TResult);

var url = obj.Url;
var content = ContentProvider.GetContent(obj);
var contentType = obj.ContentType.GetDisplayName();
var headers = HeaderProvider.GetHeaders(accessToken,obj.CustomHeaders.ToArray());

var result = RESTFul.PostInternal(obj.Url,content,contentType,headers);

返回RESTFul.ResponseProcessor< TResult>(结果);
}




我收到回复后我有这个方法来填充Reponse方法


 private static TResult ResponseProcessor< TResult>(RESTFulResponseInternal result)
其中TResult:RESTFulResponse
{
if(result.IsSuccessStatusCode)
{
var response = ContentProvider.Deserialize< TResult>(result.Content);
response.Response = result;
response.Map();

返回回复;
}
else
{
抛出新的InvalidOperationException($" RESTful Exception:{result.StatusCode} \ nnError:{result.Content}");
}
}




一切都很棒!只有一个案例 发现失败了。如果我有以下JSON:

 [
{
" userId":1,
" id" ;:1,
" title":" sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
" body":" quia et suscipit\\\
suscipit recusandae consequuntur expedita et cum\\ nreprehenderit molestiae ut ut quas totam \\\
nostrum rerum est autem sunt rem eveniet architecto"
},
{
" userId":1,
" id":2,
" title":" qui est esse",
" body"" est rerum tempore vitae\\\
sequi sint nihil reprehenderit dolor beatae ea dolores neque\\\
fugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\\\
qui aperiam non debitis possimus qui neque nisi nulla"
}
}


要反序列化为  TypiCodePostResponse类。

 

公共类TypiCodePostResponse:RESTFulResponse
{
public Post []帖子{get;组; }

public class Post
{
public int userId {get;组; }
public int id {get;组; }
公共字符串标题{get;组; }
public string body {get;组; }
}
}




不会使用我的逻辑


我需要一个包含List / List of Posts的类。我不想让Posts继承RESTfulResponse类,因为所有其余的调用元数据都将存储在每一个中,我不希望这样。



任何想法?



提前致谢,


Martin

解决方案

Martin Nikolaev,


感谢您在此发帖。


对于您的问题,如何在您提供的响应链接中为json字符串定义类?如果要使用类序列化json数据,可以复制json数据并执行以下步骤自动生成类。


单击编辑>选择性粘贴>将JSON粘贴为类。


 




最好的问候,


Wendy


Hello, I am trying to develop some code with generics, the idea is following:

We have plenty of API tests and each one of them requires some very long and complicated call, since they are hard to memorize I was thinking of a way to do that with classes. You create two classes with Request and Response and fill up the needed properties and serialize that into XML, JSON or FORM and get the results populated in the Response class.

To make this happen I have two abstract classes - RESTfulRequest and RESTfulResponse.

These two classes are to be inherited by any class that is going to be used for RESTful call.

public abstract class RESTFulRequest
    {

        #region Public Fields

        public string Url { get; set; }
        public ContentType ContentType { get; set; }
        public List<KeyValue> CustomHeaders { get; set; }

        #endregion

        #region Public Constuctors

        public RESTFulRequest()
        {
            this.CustomHeaders = new List<KeyValue>();
        }

        #endregion

    }

 public class RESTFulResponseInternal
    {
        #region Public Constructors

        /// <summary>
        /// Initializes the class with the specified status code and content.
        /// </summary>
        /// <param name="statusCode">The http status code.</param>
        /// <param name="isSuccessStatusCode">A boolean value indicating if the http response was successful.</param>
        /// <param name="content">The http response content.</param>
        public RESTFulResponseInternal (HttpStatusCode statusCode, bool isSuccessStatusCode, string content)
        {
            StatusCode = statusCode;
            IsSuccessStatusCode = isSuccessStatusCode;
            Content = content;
        }

        #endregion

        #region Public Properties

        /// <summary>
        /// Gets http status code.
        /// </summary>
        public HttpStatusCode StatusCode { get; private set; }

        /// <summary>
        /// Gets a value indicating if the http response was successful.
        /// </summary>
        public bool IsSuccessStatusCode { get; private set; }

        /// <summary>
        /// Gets the http response content.
        /// </summary>
        public string Content { get; private set; }

        #endregion
    }


Next I have an extension method for every class that inherits the Request class

public static TResult POST<TResult>(this RESTFulRequest obj, string accessToken = "")
            where TResult : RESTFulResponse, new()
        {
            if (obj == null) return default(TResult);

            var url = obj.Url;
            var content = ContentProvider.GetContent(obj);
            var contentType = obj.ContentType.GetDisplayName();
            var headers = HeaderProvider.GetHeaders(accessToken, obj.CustomHeaders.ToArray());

            var result = RESTFul.PostInternal(obj.Url, content, contentType, headers);

            return RESTFul.ResponseProcessor<TResult>(result);
        }


and after I get the response I have this method to populate the Reponse method

private static TResult ResponseProcessor<TResult>(RESTFulResponseInternal result)
            where TResult : RESTFulResponse
        {
            if (result.IsSuccessStatusCode)
            {
                var response = ContentProvider.Deserialize<TResult>(result.Content);
                response.Response = result;
                response.Map();

                return response;
            }
            else
            {
                throw new InvalidOperationException($"RESTful Exception: {result.StatusCode}\nError: {result.Content}");
            }
        }


Everything works great! Just one case  found failing. If I have following JSON:

[
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
  }
}

To Deserialize into TypiCodePostResponse class.

public class TypiCodePostResponse : RESTFulResponse { public Post[] Posts { get; set; } public class Post { public int userId { get; set; } public int id { get; set; } public string title { get; set; } public string body { get; set; } } }


Would not work with my logic

I need a class with a List/Array of Posts inside. I dont want to make Posts Inheriting the RESTfulResponse class, because then all rest call metadata will be stored in each one of them, where I do not want that.

Any ideas ?

Thanks in advance,

Martin

解决方案

Hi Martin Nikolaev,

Thank you for posting here.

For your question, how do you define the class for json string in the response link you provided? If you want to serialize the json data with classes, you could copy the json data and do the steps below to generate classes automatically.

Click Edit> Paste Special> Paste JSON As Classes.

 

Best Regards,

Wendy


这篇关于将restful响应反序列化为自定义类的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆