Search code examples
c#jsonparsingjson-deserialization

JSON deserialize array with custom objects in it


Hi this is my JSON file I would like to parse in C#:

 {
  "modelParam": {
    "defaultConfigFilePath": "../modelParam.json",
    "actionType":[
            {
            "showText": 
                {
                    "feld": "input" , 
                    "text": "Port",
                    "value": 4 
                }
            },
            {
            "showText": 
                {
                    "feld": "input" , 
                    "text": "TestTest",
                    "value": 78  
                }
            }
        ]
    }
  } 

Does anyone have an idea how to parse/deserialize this file?

Best regards C.O


Solution

  • First you have to create this c# classes.

       public class Model
    {
        public Modelparam modelParam { get; set; }
    }
    
    public class Modelparam
    {
        public string defaultConfigFilePath { get; set; }
        public Actiontype[] actionType { get; set; }
    }
    
    public class Actiontype
    {
        public Showtext showText { get; set; }
    }
    
    public class Showtext
    {
        public string feld { get; set; }
        public string text { get; set; }
        public int value { get; set; }
    }
    

    After that you can deserialize(parse) it to c# object. For this:

    var model =System.Text.Json.JsonSerializer.Deserialize<Model>("your json source");