Home > database >  Convert Flat Data from C# to JSON
Convert Flat Data from C# to JSON

Time:04-15

I have a c# class that looks something like this:

public class Item
{
    public int Id { get; set; }
    public int? ParentId { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public string Type { get; set; }
}

and i would like to convert it to json where json property name is item name and its value is item description. if some item has any children then i would like the json property name to stay as item name and the children to be added like item name:item description(the parent item description and type become empty string if it has any children, except when the type is array). The type has following values: array, string, int, object. if the item type is an array then each time a child is added to the type array item, the child is item description. so i would like those values to be added to the json array as well. if the type is string or int the json property value should be int or string. I am trying to write custom JsonSerializer but i am getting nowhere. so if i have a list with items:

List<Item> MyItems = new List<Item>()
{
    new Item { Id = 1, ParentId = null, Name = "Name1", Description = "", Type = "" },
    new Item { Id = 2, ParentId = 1, Name = "Name2", Description = "Description1", Type = "String" },
    new Item { Id = 3, ParentId = 1, Name = "Name3", Description = "", Type = "Array" },
    new Item { Id = 4, ParentId = 3, Name = "", Description = "ArrayItem1", Type = "" },
    new Item { Id = 5, ParentId = 3, Name = "", Description = "ArrayItem2", Type = "" },
    new Item { Id = 6, ParentId = 3, Name = "", Description = "ArrayItem3", Type = "" },
    new Item { Id = 7, ParentId = null, Name = "Name4", Description = "5", Type = "Int" },
};

then the json should like this:

{
   "name1":{
      "name2":"description1",
      "name3":[
         "ArrayItem1",
         "ArrayItem2",
         "ArrayItem1"
      ]
   },
   "name4":5
}

CodePudding user response:

Here's an extension method that I think does what you want:

public static class Ex
{
    public static string ToJson(this List<Item> items)
    {
        var lookup = items.ToLookup(x => x.ParentId);
        JObject ToJson(int? parentId)
        {
            JProperty ToProperty(Item item)
            {
                switch (item.Type)
                {
                    case "":
                        return new JProperty(item.Name, ToJson(item.Id));
                    case "String":
                        return new JProperty(item.Name, item.Description);
                    case "Array":
                        return new JProperty(item.Name, lookup[item.Id].Select(x => x.Description).ToArray());
                    case "Int":
                        return new JProperty(item.Name, int.Parse(item.Description));
                    default:
                        return new JProperty(item.Name);
                }
            }
            return new JObject(lookup[parentId].Select(x => ToProperty(x)));
        }
        var output = ToJson(null);
        var text = Newtonsoft.Json.JsonConvert.SerializeObject(output, Newtonsoft.Json.Formatting.Indented);
        return text;
    }
}

I run it like this:

List<Item> MyItems = new List<Item>()
{
    new Item { Id = 1, ParentId = null, Name = "Name1", Description = "", Type = "" },
    new Item { Id = 2, ParentId = 1, Name = "Name2", Description = "Description1", Type = "String" },
    new Item { Id = 3, ParentId = 1, Name = "Name3", Description = "", Type = "Array" },
    new Item { Id = 4, ParentId = 3, Name = "", Description = "ArrayItem1", Type = "" },
    new Item { Id = 5, ParentId = 3, Name = "", Description = "ArrayItem2", Type = "" },
    new Item { Id = 6, ParentId = 3, Name = "", Description = "ArrayItem3", Type = "" },
    new Item { Id = 7, ParentId = null, Name = "Name4", Description = "5", Type = "Int" },
};

Console.WriteLine(MyItems.ToJson());

And I get this out:

{
  "Name1": {
    "Name2": "Description1",
    "Name3": [
      "ArrayItem1",
      "ArrayItem2",
      "ArrayItem3"
    ]
  },
  "Name4": 5
}

CodePudding user response:

You can try to serialize the object to json.

List<userdetails> details = new List<userdetails>();
userdetails user = new userdetails();
details.Add(new userdetails { userid = 1, username = "suresh", location = "chennai" });
string strserialize = JsonConvert.SerializeObject(details);
  • Related