-2

I'm trying to convert

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

to model class that is AdvanceEventsDto

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

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

and EventDto calss is

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

json is

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

when i'm trying to get values like follows

 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];

but i'm getting following error The requested operation requires an element of type 'Array', but the target element has type 'Object'.

I'm trying to map AdvanceEvents.json values to class AdvanceEventsDto and class EventsDto

dbc
  • 104,963
  • 20
  • 228
  • 340
  • `dynamic` should be a last resort. You have a wellknown model, so there is absolutely no reason to use dynamic. If your JSON doesn't match your model, copy your JSON to the clipboard and use Edit/Paste JSON as classes to get a good model. – Neil Jan 14 '23 at 17:57
  • now I'm getting "The JSON value could not be converted to xxxx.BasicAuth.Api.Models.EventsDto[]. Path: $.Events[0] | LineNumber: 2 | BytePositionInLine: 12." – Nuwan Indika Jan 14 '23 at 18:20
  • Are you absolutely sure your actual JSON matches that in the question? – Neil Jan 16 '23 at 11:50

1 Answers1

0

fix the class

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

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

and use this code

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

string[] events = advanceEvent.Events;
Serge
  • 40,935
  • 4
  • 18
  • 45