-2

I have a JSON file that lists items that I want to use as the properties in a class. For example,

{
  "id": "cmnsz41@fhfitsocj0wgjeajkgbd#4c4mgkf1vwbh_",
  "displayName": "Archive",
  "parentFolderId": "cmnsz41@fhfitsocj0wgjeajkgbd#4c4mgkf1vwbh_",
  "childFolderCount": 0,
  "unreadItemCount": 0,
  "totalItemCount": 0
}

becomes

public string Archive
{
    get
    {
        return "cmnsz41@fhfitsocj0wgjeajkgbd#4c4mgkf1vwbh_";
    }
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
espo
  • 67
  • 6
  • 5
    It's unclear what your question is. If you're having trouble with something, you'll need to be more specific about what. Parsing JSON is mostly a solved problem; code generation is a little more involved (if that's what you're after), but also has solutions (T4 templates, the new C# source generators). This is just two code snippets. – Jeroen Mostert Sep 10 '20 at 13:44
  • You mean you want to generate a new class declaration based on the properties? Or you want to deserialise the JSON to an instance of a ready-made class? It's a little unclear, but the latter is the far more common requirement, and easily solved with a JSON-parsing library such as JSON.NET - see https://www.newtonsoft.com/json/help/html/DeserializeObject.htm – ADyson Sep 10 '20 at 13:48
  • Possible duplicate of [How to auto-generate a C# class file from a JSON string](https://stackoverflow.com/a/21611680/1260204) – Igor Sep 10 '20 at 13:52

1 Answers1

1

Create a class and deserialize your json to the class and the properties will automatically be set.

  public class Root    
    {
        public string id { get; set; } 
        public string displayName { get; set; } 
        public string parentFolderId { get; set; } 
        public int childFolderCount { get; set; } 
        public int unreadItemCount { get; set; } 
        public int totalItemCount { get; set; } 
     }

    var json = @"{
      "id": "cmnsz41@fhfitsocj0wgjeajkgbd#4c4mgkf1vwbh_",
      "displayName": "Archive",
      "parentFolderId": "cmnsz41@fhfitsocj0wgjeajkgbd#4c4mgkf1vwbh_",
      "childFolderCount": 0,
      "unreadItemCount": 0,
      "totalItemCount": 0
     }"

     var root = JsonConvert.DeserializeObject<Root>(json);

 
Kevin
  • 2,566
  • 1
  • 11
  • 12