Map JSON object to C# class property array

强颜欢笑 提交于 2021-01-29 18:00:30

问题


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());

回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/58364283/map-json-object-to-c-sharp-class-property-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!