Web Api .Net客户端 - 对象未反序列化 [英] Web Api .Net Client - Object not deserialising

查看:100
本文介绍了Web Api .Net客户端 - 对象未反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



这是我昨天问过的以下问题:

使用Web API返回复杂对象 [ ^ ]

非常感谢 KornfeldEliyahuPeter [ ^ ]为他提供帮助。



我现在正在创建一个控制台应用程序来访问Web Api。我使用了 Calling-a-web-api - 来自网络客户端 [ ^ ]来自Microsoft作为我创建客户端的模板,但是在尝试对我的对象进行反序列化时遇到了问题。



为了省去这里的问题,我的对象结构是:



Hi all,

This is a follow on from the following question I asked yesterday:
Return complex objects with Web API[^]
Thanks very much to KornfeldEliyahuPeter[^] for his help there.

I'm now creating a console application to access the Web Api. I have used Calling-a-web-api-from-a-net-client[^] from Microsoft as my template for creating my client but I'm getting an issue when it tries to de-serialise my object.

To save having to jump between questions here is my object structure:

public interface IMyFileInterface
{
    string FileName {get;set;}
    MyEnum FileType {get;set;
    DateTime UploadDate {get;set;}
}



课程:


Classes:

[DataContract]
[KnownType(typeof(FooFileModel))]
public class ReturnModel
{
   [DataMember]
   public string Name {get;set;}
   [DataMember]
   public List<IMyFileInterface> LatestFiles {get;set;}
}

[DataContract]
public class FooFileModel : IMyFileInterface
{
    [DataMember]
    string FileName {get;set;}
    [DataMember]
    MyEnum FileType {get;set;
    [DataMember]
    DateTime UploadDate {get;set;}

}





我的api调用的地址类似于:http:// localhost:12345 / API / API / GetReport



我的客户端代码如下:





My api call is to an address similar to: "http://localhost:12345/API/API/GetReport"

My client code looks like this:

private async Task<UtilitiesReportModel> GetReportModalAsync()
{
   using (var client = new HttpClient())
   {
          client.BaseAddress = new Uri("http://localhost:12345/");
          client.DefaultRequestHeaders.Accept.Clear();
          client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                Task<HttpResponseMessage> response =  client.GetAsync("API/API/GetReport");
                if (response.Result.IsSuccessStatusCode)
                {
                    UtilitiesReportModel reportModel = await response.Result.Content.ReadAsAsync<UtilitiesReportModel>();
                    Debug.WriteLine(reportModel.Name);
                    Debug.WriteLine(reportModel.LatestUploads.Count);
                    return reportModel;
                }
                return null;

            }
        }





从我的主要方法调用以下内容:< br $> b $ b



Which is called from my "main" method as follows:

var res = GetReportModalAsync();
res.Wait();
var theRes = res.Result;





但是,当res.Wait()触发时,我收到以下错误:



无法创建Common.Objects.IMyFileInterface类型的实例。 Type是接口或抽象类,无法实例化。路径'LatestUploads [0] .SurveyType',第1行,第220位。



(我不知道它是否相关但是SurveyType是一个自定义枚举。)



现在我理解错误说的是什么,出于某种原因,当它试图反序列化它试图创建一个实例时界面,我们都知道这是不可能的。如何告诉它创建它的原始类的实例?当我查看来自API调用的响应时,它具有原始数据类型。



任何帮助都将受到赞赏,因为我希望能够对接口进行编码如果我可以帮助它,不要硬编码。



当我在网络浏览器中调用api时,它会在以下XML中显示结果。 (我知道评论已在JSon中提出要求)。





However, when res.Wait() triggers I get the following error:

Could not create an instance of type Common.Objects.IMyFileInterface. Type is an interface or abstract class and cannot be instantiated. Path 'LatestUploads[0].SurveyType', line 1, position 220.

(I don't know if it is relevant but SurveyType is a custom enum).

Now I understand what the error says, for some reason when it tries to de-serialise it is trying to create an instance of an interface, as we all know this is impossible. How do I tell it to create an instance of it's original class? When I look at the response from the API call it has the original data type in.

Any help would be appreciated as I would like to be able to code against interfaces and not hard code the classes if I can help it.

When I call the api in a web browser it displays the result in the following XML. (I know the comment has asked for it in JSon).

<ReportModel xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Common.Objects">
    <CurrentMonth i:nil="true"/>
    <LastRefresh>0001-01-01T00:00:00</LastRefresh>
    <LatestUploads xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
        <d2p1:anyType i:type="FooFileModel">
            <DateTimeUploaded>2014-12-08T14:23:37.243</DateTimeUploaded>
            <FileName>05122014 cleaned for loading.xlsx</FileName>
            <NumberOfEntries>76</NumberOfEntries>
            <SurveyType>TypeA</SurveyType>
        </d2p1:anyType>
        <d2p1:anyType i:type="FooFileModel">
            <DateTimeUploaded>2014-12-05T12:04:47.877</DateTimeUploaded>
            <FileName>04122014 Cleaned for loading.xlsx</FileName>
            <NumberOfEntries>5</NumberOfEntries>
            <SurveyType>TypeB</SurveyType>
        </d2p1:anyType>
        <d2p1:anyType i:type="FooFileModel">
            <DateTimeUploaded>2014-12-05T12:05:28.14</DateTimeUploaded>
            <FileName>04122014 Cleaned for loading.xlsx</FileName>
            <NumberOfEntries>6</NumberOfEntries>
            <SurveyType>TypeC</SurveyType>
        </d2p1:anyType>
    </LatestUploads>
    <Name>Site1</Name>
</ReportModel>





如果我打电话给response.Result.Content.Rea dAsStringAsync();



我得到以下内容,我相信这是Json的回复:





If I call "response.Result.Content.ReadAsStringAsync();

I get the following out, which I believe is the Json response:

{"$type":"Common.Objects.ReportModel, Common",
"Name":"Site1",
"LatestUploads":[
    {"$type":"Common.Objects.FooFileModel, Common",
     "SurveyType":2,
     "FileName":"08122014 Cleaned for loading.xlsx",
     "DateTimeUploaded":"2014-12-09T14:02:36.147",
     "NumberOfEntries":69},
    {"$type":"Common.Objects.FooFileModel, Common",
     "SurveyType":1,
     "FileName":"08122014 Cleaned for loading.xlsx",
     "DateTimeUploaded":"2014-12-09T14:03:41.11",
     "NumberOfEntries":11},
    {"$type":"Common.Objects.FooFileModel, Common",
     "SurveyType":2,
     "FileName":"05122014 cleaned for loading.xlsx",
     "DateTimeUploaded":"2014-12-08T14:23:37.243",
     "NumberOfEntries":76}],
"CurrentMonth":null,"LastRefresh":"0001-01-01T00:00:00"}

推荐答案

type:Common.Objects.ReportModel,Common,
Name:Site1,
LatestUploads:[
{
type":"Common.Objects.ReportModel, Common", "Name":"Site1", "LatestUploads":[ {"


type:Common.Objects.FooFileModel,Common,
SurveyType:2,
FileName:08122014已清除loading.xlsx ,
DateTimeUploaded:2014-12-09T14:02:36.147,
NumberOfEntries:69},
{
type":"Common.Objects.FooFileModel, Common", "SurveyType":2, "FileName":"08122014 Cleaned for loading.xlsx", "DateTimeUploaded":"2014-12-09T14:02:36.147", "NumberOfEntries":69}, {"


类型:Common.Objects.FooFileModel,Common,
SurveyType:1,
FileName:08122014已清除loading.xlsx,
DateTimeUploaded:2014 -12-09T14:03:41.11,
NumberOfEntries:11},
{
type":"Common.Objects.FooFileModel, Common", "SurveyType":1, "FileName":"08122014 Cleaned for loading.xlsx", "DateTimeUploaded":"2014-12-09T14:03:41.11", "NumberOfEntries":11}, {"


这篇关于Web Api .Net客户端 - 对象未反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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