简体   繁体   中英

Map JSON object to C# class property array

JSON

{
"SoftHoldIDs": 444,
"AppliedUsages": [
    {
        "SoftHoldID": 444,
        "UsageYearID": 223232,
        "DaysApplied": 0,
        "PointsApplied": 1
    }
],
"Guests": [
    1,
    2
]

} In the above JSON SoftholdIDs is integer and AppliedUsages is class array property in C# Model

Issue is --How we can map JSON to class property. Class code

  public class ReservationDraftRequestDto
{

    public int SoftHoldIDs { get; set; }
    public int[] Guests { get; set; }
    public AppliedUsage[] AppliedUsages { get; set; }

}


public class AppliedUsage
{
    public int SoftHoldID { get; set; }
    public int UsageYearID { get; set; }
    public int DaysApplied { get; set; }
    public int PointsApplied { get; set; }
}

Tried below code for mapping

ReservationDraftRequestDto reservationDto = null;

        dynamic data  = await reservationDraftRequestDto.Content.ReadAsAsync<object>();
                    reservationDto = JsonConvert.DeserializeObject<ReservationDraftRequestDto>(data.ToString());

You need to change

dynamic data  = await reservationDraftRequestDto.Content.ReadAsAsync<object>();

to

string data = await reservationDraftRequestDto.Content.ReadAsStringAsync();

this will read your response as string

then do

reservationDto = JsonConvert.DeserializeObject<ReservationDraftRequestDto>(data);

this work

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
         class Program
    {
        static void Main(string[] args)
        {
            string json = @"{""SoftHoldIDs"": 444,""AppliedUsages"": [    {""SoftHoldID"": 444,""UsageYearID"": 223232,""DaysApplied"": 0,""PointsApplied"": 1}],""Guests"": [ 1, 2]}";

            Rootobject reservationDto = JsonConvert.DeserializeObject<Rootobject>(json.ToString());

            Debug.WriteLine(reservationDto.SoftHoldIDs);
            foreach (var guest in reservationDto.Guests)
            {

                Debug.WriteLine(guest);
            }

        }
    }

    public class Rootobject
    {
        public int SoftHoldIDs { get; set; }
        public Appliedusage[] AppliedUsages { get; set; }
        public int[] Guests { get; set; }
    }

    public class Appliedusage
    {
        public int SoftHoldID { get; set; }
        public int UsageYearID { get; set; }
        public int DaysApplied { get; set; }
        public int PointsApplied { get; set; }
    }


}

First create class copying json as classwith visualstudio. Next you have double quote in json respons so deal with it. Json.NET: Deserilization with Double Quotes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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