Chanchal Chanchal - 4 months ago 50
JSON Question

Deserializing list of items

I have following sample Json string:

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


I need to deserialize the same but I don't want to keep my class name as following:

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


I want to keep custom class name such DataDetails. How that can be achieved in c#?

Answer

I don't quite understand what your question is but you can just change the class names to whatever you want. Below is a working example.

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