0

This is my first time using a library outside of .NET let-alone JSON.Net so excuse my beginner question. I am trying to deserialize some AWS data into an object using the JSON.Net library but keep getting this error specifically with the IP address in the json file.

Example AWS Data

    {
  "ip_prefix": "205.251.254.0/24",
  "region": "GLOBAL",
  "service": "CLOUDFRONT"
},
{
  "ip_prefix": "216.137.32.0/19",
  "region": "GLOBAL",
  "service": "CLOUDFRONT"
}

Here is an example of my C#:

class AWS
{
    public string ipprefix;
    public string region;
    public string service;
}


   class DataGathering
{
    public List<AWS> GetIPData(string filename)
    {
        List<AWS> ipdata = new List<AWS>();
        using (StreamReader reader = new StreamReader(filename))
        {
            string json = reader.ReadToEnd();
            ipdata = JsonConvert.DeserializeObject<List<AWS>>(json);
        }

        return ipdata;
    }

Any help is much appreciated

Kristian
  • 90
  • 6
  • The issue that I am having is that the region and service values are being stored, but the IP addresses are not. – Kristian Sep 05 '17 at 01:59

1 Answers1

1

Since the property name in the data has an underscore it is likely that it is not translating that to the class. This topic shows how you can define what the json property names are Json.Net: JsonSerializer-Attribute for custom naming

Aaron Roberts
  • 1,342
  • 10
  • 21
  • The issue that I am having is that the region and service values are being stored, but the IP addresses are not. – Kristian Sep 05 '17 at 01:59
  • 1
    yep - since the ip_prefix property in the json object has an underscore and the property on your AWS object does not, it is not able to match that data to the property. Use tha JsonProperty attribute with the PropertyName to tell the serializer that "ip_prefix" is expected to map to the `ipprefix` property in your class – Aaron Roberts Sep 05 '17 at 02:06
  • thanks for that, I understand what you mean now. However it doesn't seem that it is attaching to the Json object. This is what I changed it to: [JsonProperty(PropertyName = "IPPrefix")] public string IPPrefix { get; set; } – Kristian Sep 05 '17 at 03:38
  • 1
    Close, since the property name in the json data is "ip_prefix" the attribute declaration should look like this [JsonProperty(PropertyName = "ip_prefix")] – Aaron Roberts Sep 05 '17 at 03:47