反序列化项列表

时间:2016-07-12 21:32:29

标签: c# .net json serialization deserialization

我有以下示例Json字符串:

{"Items":[{"Id":"20","CaptureCategoryTypeId":5021,"Name":"24270","Description":"FSH  CARRIBEAN CAPTAIN","IsEnabled":true}],"TotalResults":0}

我需要对其进行反序列化,但我不想将我的班级名称保留如下:

public class Item
{
    public string Id { get; set; }
    public int CaptureCategoryTypeId { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public bool IsEnabled { get; set; }
}

public class RootObject
{
    public List<Item> Items { get; set; }
    public int TotalResults { get; set; }
}

我想保留自定义类名,例如DataDetails。如何在c#中实现?

1 个答案:

答案 0 :(得分:0)

我不太明白你的问题是什么,但你可以将类名更改为你想要的任何名称。以下是一个工作示例。

using Newtonsoft.Json;
using System;
using System.Collections.Generic;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            string JSONInput = @"{""Items"":[{""Id"":""20"",""CaptureCategoryTypeId"":5021,""Name"":""24270"",""Description"":""FSH CARRIBEAN CAPTAIN"",""IsEnabled"":true}],""TotalResults"":0}";
            BlahObject deserializedProduct = JsonConvert.DeserializeObject<BlahObject>(JSONInput);
            Console.ReadKey();
        }
    }

    public class DataDetails
    {
        public string Id { get; set; }
        public int CaptureCategoryTypeId { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public bool IsEnabled { get; set; }
    }

    public class BlahObject
    {
        public List<DataDetails> Items { get; set; }
        public int TotalResults { get; set; }
    }
}