Search code examples
jsonjson.netjsonconvert

Deserialize an array within an array in JSON


I have the following JSON file that I want to deserialize into an object

{
"InputFileFolder": "D:\\MontlyTransactions\\",
"TransactionGroups":
[
    {
        "Name": "Income", 
        "FilterString": "Type=@0 and Amount>@1 and (Description.Contains(@2) or Description.Contains(@3))",
        "Arguments": ["BAC",0,"REF1","REF2"]
    },
    {
        "Name": "Household Bills", 
        "FilterString": "Type=@0 and Amount<@1 and Amount.Contains(@2)",
        "Arguments": ["S/O",0,[16600,72000,15000]]
    }
]

}

The object I am trying to convert to is as below:

    public class Configuration
{
    public string InputFileFolder { get; set; }
    public TransactionGroup[] TransactionGroups { get; set; }
}
   public class TransactionGroup
{
    public string Name { get; set; }
    public string FilterString { get; set; }
    public string[] Arguments { get; set; }
}

using the below snippet:

this.Configuration = JsonConvert.DeserializeObject<Configuration>(configurationString);

However the array within the second argument is returned as a Newtonsoft.Json.Linq.Array instead of an object[] which is what I was expecting.

Any suggestions would be hugely appreciated.


Solution

  • You need to start by checking the Arguement elements in Json. For example, from the Json given in OP

     'Arguments': ['BAC',0,'REF1','REF2']   
    

    and

     'Arguments': ['S/O',0,[16600,72000,15000]]
    

    As you can observe the, elements involved are not an array of strings. In fact, it contains strings, numbers and sub arrays of numbers as well.

    So you need to change your class definition as

    public class TransactionGroup
    {
        public string Name { get; set; }
        public string FilterString { get; set; }
        public object[] Arguments { get; set; } // Change here
    }
    

    That would help you deserialize the Json successfully.