簡體   English   中英

json 反序列化動態將其轉換為 model

[英]json Deserialize dynamic to convert it to model

我正在嘗試轉換

dynamic AdvanceEvent = JsonSerializer.Deserialize<dynamic>(File);

到 model class 即 AdvanceEventsDto

 public class AdvanceEventsDto
    {
        /// <summary>
        ///  The Event List
        /// </summary>
        public   EventsDto[] Events { get;set;}

        /// <summary>
        /// The Winner
        /// </summary>
        public string Winner { get; set; }
    } 

EventDto 類是

public class EventsDto
    {
        /// <summary>
        /// The Events
        /// </summary>
        public string Events { get; set; }
    }

json 是

{
  "Events" : [
    "France",
    "Netherlands",
    "Argentina",
    "Brazil",
    "France",
    "Argentina",
    "Qatar",
    "Brazil",
    "Germany",
    "Japan",
    "Brazil",
    "Portugal",
    "Japan",
    "Japan",
    "Brazil"
  ],
  "Winner" : "Brazil"
}

當我試圖獲得如下值時

 string  FilePath = System.IO.Path.GetFullPath(@"..\..\Data\AdvanceEvents.json");
                string  File = System.IO.File.ReadAllText( FilePath);
                dynamic AdvanceEvent = JsonSerializer.Deserialize<dynamic>( File);
                var events = AdvanceEvent[0];

但我收到以下錯誤The requested operation requires an element of type 'Array', but the target element has type 'Object'.

我正在嘗試將 map AdvanceEvents.json 值更改為 class AdvanceEventsDto 和 class EventsDto

修復 class

public class AdvanceEventsDto
    {
        /// <summary>
        ///  The Event List
        /// </summary>
        public  string[] Events { get;set;}

        /// <summary>
        /// The Winner
        /// </summary>
        public string Winner { get; set; }
    } 

並使用此代碼

AdvanceEventsDto advanceEvent = JsonSerializer.Deserialize<AdvanceEventsDto>(File);

string[] events = advanceEvent.Events;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM