将JSON对象映射到C#类属性数组 [英] Map JSON object to C# class property array

查看:91
本文介绍了将JSON对象映射到C#类属性数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JSON

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

} 在上面的JSON中,SoftholdIDs是整数,而AppliedUsages是C#模型中的类数组属性

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

问题是-如何将JSON映射到类属性. 班级代码

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

尝试以下代码进行映射

ReservationDraftRequestDto reservationDto = null;

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

推荐答案

这项工作

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


}

首先使用visualstudio创建将json复制为类的类. 接下来,您在json响应中有双引号,因此请对其进行处理. Json.NET:使用双引号进行反序列化

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

这篇关于将JSON对象映射到C#类属性数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆