Making this JSON to a Class

Viewed 64

Good day, I just can't seem to wrap on this, I have this JSON document in mind, but how can I do it as a class?

the JSON goes like this :

{
    "name": "stacking",
    "id": "12345",
    "moreDetails" : {
         "new_item_0" : {
             "id": "abcdefg"
         },
         "new_item_1" : {
             "id": "hujklmn"
         },
         "new_item_n" : {
             "id": "opqrtsu"
         }
     }
}

Where "moreDetails" have an infinite amount of "new_item_n" in it.

Gonna use this class as a format of my database in MongoDB.

The class I have in mind goes like this:

public string name;
public string id;
// beyond here I have no idea
3 Answers

You can use Dictionary<string, class>:

public partial class Root
{
    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("id")]
    public string Id { get; set; }

    [JsonProperty("moreDetails")]
    public Dictionary<string, Item> MoreDetails { get; set; }
}

public class Item
{
    [JsonProperty("id")]
    public string Id { get; set; }
}

So this:

var x = new Root
{
    Name = "stacking",
    Id = "1",
    MoreDetails = new Dictionary<string, Item> {
        {"new_item_0", new Item {Id = "itemId"}}
    }

};
JsonConvert.SerializeObject(x, Newtonsoft.Json.Formatting.Indented);

results in:

{
  "name": "stacking",
  "id": "1",
  "moreDetails": {
    "new_item_0": {
      "id": "itemId"
    }
  }
}

Try using KeyValuePair where ObjectType is the class that describes the object behind your new_item_n

List<KeyValuePair<string,ObjectType>>

Or use the dictionary as the answer of Guru Strom!

Well since MovieDetails will be an infinite and dynamic it should be a dictionary. So something like this:

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

namespace Scratch
{
    class Program
    {
        class Thing
        {
            public string Name { get; set; }
            public string Id { get; set; }
            public Dictionary<string, Item> MoreDetails { get; set; }
         }

        class Item
        {
            public string Id { get; set; }
        }

        static void Main(string[] args)
        {
            var json = File.ReadAllText("f.json");
            var thing = JsonConvert.DeserializeObject<Thing>(json);

            Console.WriteLine(thing.Name);
        }
    }
}
Related