0

I have the following line which imports my JSON file into an object:

RootObject rootObject = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(jsonFromFile);

This works for 90% of the JSON document but it fails on the below sections of the JSON document (by fail I mean I get NULL's, no error is thrown):

"myData": {
        "AAA BBBB (AA/BBB) A": [
            {
                "commodity": "value1",
                "direction": "INPUT",
                "start": "2019-11-15 15:04:00+0000",
                "end": "2019-11-15 16:04:00+0000",
                "max": 0.0,
                "description": "FAR not in"
            }
        ],
        "AAA BBBB (AA/BBB) B": [
            {
                "commodity": "value2",
                "direction": "INPUT",
                "start": "2019-11-15 15:04:00+0000",
                "end": "2019-11-15 16:04:00+0000",
                "max": 0.0,
                "description": "FAR not in yet"
            }
        ]
}

I suspect this is due to the section names as they contain brackets and slashes.

I used Visual Studio to generate classes based on the JSON document and it named these classes:

AAABBBBAABBBA and AAABBBBAABBBB

Is there anyway to handle this so my app picks up this data?

UPDATE:

The RootObject has the following within it:

public MyData myData{ get; set; }

And MyData contains:

public class MYData
    {
        public int Id { get; set; }
        public List<AAABBBBAABBBA1> AAABBBBAABBBA{ get; set; }
        public List<AAABBBBAABBBB1> AAABBBBAABBBB{ get; set; }
    }
Pavel Anikhouski
  • 21,776
  • 12
  • 51
  • 66
Silentbob
  • 2,805
  • 7
  • 38
  • 70

1 Answers1

1

if you are using Newtonsoft.Json, then you'll need to add these properties to your class

public  class MyData
{
    [JsonProperty("AAA BBBB (AA/BBB) A")]
    public List<MyObject> AAABBBBAABBBA{ get; set; }
    [JsonProperty("AAA BBBB (AA/BBB) B")]
    public List<MyObject> AAABBBBAABBBB{ get; set; }
}

by default, newtonsoft.json does not deserialize correctly if the name of the variable doesnt exactly match.

I think you can use a single object for both of the lists

public  class MyObject
{
    public  string commodity { get; set; }
    public  string direction { get; set; }

...
}
Jawad
  • 11,028
  • 3
  • 24
  • 37