简体   繁体   English

将JSON对象绑定到ViewModel

[英]Binding JSON object to a ViewModel

How can I map JSON object (returned from Web API) to a View Model. 如何将JSON对象(从Web API返回)映射到视图模型。 [ I am using automapper to map my c# business objects to View Model. [我正在使用自动映射器将c#业务对象映射到视图模型。 I am looking for somthing similar to map JSON to View Model] 我正在寻找类似于将JSON映射到视图模型的东西]

I am getting the following error : "Cannot deserialize the current JSON object into type 'System.Collections.Generic.IEnumerable`1[CLAW.BLL.MLAReports.Models.CMAReport]' because the type requires a JSON array". 我收到以下错误:“无法将当前JSON对象反序列化为类型'System.Collections.Generic.IEnumerable`1 [CLAW.BLL.MLAReports.Models.CMAReport]',因为该类型需要JSON数组”。

Here's the signature for my controller in Webapi. 这是我在Webapi中控制器的签名。

namespace ReportsAPI.Controllers
{
    public class ReportsController : ApiController
    {
    [HttpPost]
    public CMAReportVM Reports([FromBody] StatsCriteria criteria)
    {
      var cmaReport = Service3.GetCMAReport(criteria.Masnums);
       //Create Map to enable mapping business object to View Model
                 Mapper.CreateMap<CMAReport, CMAReportVM>();
       // Maps model to VM model class 
                 var cmaVM = Mapper.Map<CMAReport, CMAReportVM>(cmaReport);
      reutn cmaVM; 
    }
}
}

Here's the signature for the controller at client side : 这是客户端控制器的签名:

 namespace MASReports.Controllers
    {
        public ActionResult Reports(StatsCriteria criteria)
            {
             var client = new HttpClient();
             client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
             var response = client.PostAsJsonAsync("http://localhost:52765/api/reports", criteria.Masnums.ToString()).Result;

// The below line I get error.
            var represlt= response.Content.ReadAsAsync<IEnumerable<CMAReportVM>>().Result;

             return View("CMAReportVM", represlt);
            }
    }


Here's the signature for the model :


    namespace MLAReports.Models
    {
        public class CMAReportVM:ReportsVM
        {
            public CMAReportVM()    {}
            public List<Cma_Item> CmaList { get; set; }
            public string TimeStampString { get; set; }
            public Dictionary<string, string> CriteriaNameValue { get; set; }
        }  
    }


    namespace CLAW.BLL.MLAReports.Models
    {
        public class Cma_Item : IStatsGridable<Cma_Fields>
        { 
            public Cma_Item()            {}

            #region Properties and Fields
            public string PropTypeName { get; set; }
            public string StatusName { get; set; }
            public string LowP { get; set; }
            public string LowXStLP { get; set; }
            public string HighP { get; set; }
            public decimal? AvgLPFnl { get; set; }
            public decimal? AvgSPFnl { get; set; }    
            #endregion

            #region IStatsGrid Properties


            public List<string> Headers
            {
                get
                { return _headers;     }
                set
                { _headers = value;    }
            }    
            private IEnumerable<Cma_Fields> _rowModels;
            public IEnumerable<Cma_Fields> RowModels
            {
                get
                {      return _rowModels;}
                set
                {     _rowModels = value;}
            }

            private List<string> _headers;
            private string _id;
            #endregion

        }
    }

    namespace CLAW.BLL.MLaReports.Models
    {
        public interface IStatsGridable<T>
        {
             List<string> Headers { get; set; }
             string Id { get; set; }
             IEnumerable<T> RowModels { get; set; }
        }
    }


    namespace CLAW.BLL.MLAReports.Models
    {
        public class Cma_Fields
        {

            public Cma_Fields()         {   }

            #region Properties and Fields
            public string Mlanum { get; set; }
            public string Address { get; set; }
            public string BR { get; set; }
            public string BA { get; set; }
            public string SF { get; set; }

            public string TRId
            {
                get
                { return _trid;     }
                set
                {_trid = value;     }
            }
          #endregion
        }
    }

InnerException : InnerException:

{"Cannot deserialize the current JSON object (eg {\\"name\\":\\"value\\"}) into type 'System.Collections.Generic.IEnumerable`1[CLAW.BLL.MLAReports.Models.CMAReport]' because the type requires a JSON array (eg [1,2,3]) to deserialize correctly.\\r\\nTo fix this error either change the JSON to a JSON array (eg [1,2,3]) or change the deserialized type so that it is a normal .NET type (eg not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.\\r\\nPath 'CmaList', line 1, position 11."} {“无法反序列化当前JSON对象(例如{\\“ name \\”:\\“ value \\”})为类型'System.Collections.Generic.IEnumerable`1 [CLAW.BLL.MLAReports.Models.CMAReport]',因为类型需要JSON数组(例如[1,2,3])才能正确反序列化。\\ r \\ n要解决此错误,请将JSON更改为JSON数组(例如[1,2,3])或更改反序列化类型,以便可以从JSON对象反序列化的是普通的.NET类型(例如,不是整数的原始类型,不是数组或List的集合类型),还可以将JsonObjectAttribute添加到该类型中,以强制从JSON对象。\\ r \\ nPath'CmaList',第1行,位置11。“}

Your reports controller signature is returning a single item 您的报表控制器签名返回单个项目

public CMAReportVM Reports([FromBody] StatsCriteria criteria)

but you're trying to read it as IEnumerable 但您尝试将其读取为IEnumerable

var represlt= response.Content.ReadAsAsync<IEnumerable<CMAReportVM>>().Result;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM