Waddaulookingat
Waddaulookingat

Reputation: 387

Why am I getting a NULL back from my JSON deserialization?

I have a JSON file that looks like this:

{
  "dailyNews": [
    {
      "string": "D5FCF84D-B1A2-4172-9A93-E88342AA9E3C",
      "updateDate": "2019-04-24T00:00:00Z",
      "titleText": "something",
      "mainText": "sometihng ",
      "redirectionUrl": " "
    },
    {
      "string": "D5FCF84D-B1A2-4172-9A93-E88342AA9E3C",
      "updateDate": "2019-04-24T00:00:00Z",
      "titleText": "something1",
      "mainText": "sometihng2",
      "redirectionUrl": " "
    },
    {
      "string": "D5FCF84D-B1A2-4172-9A93-E88342AA9E3C",
      "updateDate": "2019-04-24T00:00:00Z",
      "titleText": "something3",
      "mainText": "sometihng4",
      "redirectionUrl": " "
    }
  ]
}

I have a C# class that I generated using JSON2CSharp. This class looks like this:

public partial class TodaysNews
{
    [JsonProperty("string")]
    public string String { get; set; }

    [JsonProperty("updateDate")]
    public DateTimeOffset UpdateDate { get; set; }

    [JsonProperty("titleText")]
    public string TitleText { get; set; }

    [JsonProperty("ImageSrc")]
    public Uri ImageSrc { get; set; }

    [JsonProperty("mainText")]
    public string MainText { get; set; }

    [JsonProperty("redirectionUrl")]
    public Uri RedirectionUrl { get; set; }
}

public class DailyNewsList
{
    public List<TodaysNews> transactions { get; set; }
   // public int count { get; set; }
}

This is the code that will deserialize:

public static DailyNewsList FromJson(string json) => 
    JsonConvert.DeserializeObject<TodaysNews>(json, S3Reader.Converter.Settings);

Everything works fine; the object TodaysNews is initialized, however the List object transactions is null. I totally don't understand why?

Upvotes: 0

Views: 39

Answers (1)

Brian Rogers
Brian Rogers

Reputation: 129697

In your DailyNewsList class, the transactions property name doesn't match what is in the JSON, which is dailyNews. You can fix this by decorating the transactions property with a [JsonProperty] attribute like you have done in your TodaysNews class:

public class DailyNewsList
{
    [JsonProperty("dailyNews")]
    public List<TodaysNews> transactions { get; set; }
}

Also, in your FromJson method, you should be deserializing to a DailyNewsList not a TodaysNews:

public static DailyNewsList FromJson(string json) => 
    JsonConvert.DeserializeObject<DailyNewsList>(json, S3Reader.Converter.Settings);

Fiddle: https://dotnetfiddle.net/5pihJE

Upvotes: 1

Related Questions