0

We are trying to deserialize Bitly data and select some values using linq operators. But it shows System.Nullreference.Exception in anonymous class

Below is our code

static void Main(string[] args)
{
    var fileData = File.ReadAllLines("bitlyfile.txt");
    var singleRow = fileData.Select(ToJson).ToList();
    singleRow.ToList().ForEach(Print);

    singleRow
       .GroupBy(b => b.Country)
       .OrderByDescending(g => g.Count())
       .Take(10)
       .Select(g => new { CountryName = g.Key, Users = g.Count() })
       .ToList()
       .ForEach(Print);

    Console.ReadKey();
}

public static Bitly ToJson(string json)//
{
    return JsonConvert.DeserializeObject<Bitly>(json);
}
public static void Print(object obj)
{

    Console.WriteLine(obj);
}

class Bitly
{
    [JsonProperty("c")]
    public string Country { get; set; }
    public override string ToString()
    {
        return Country;
    }
}

Here is our bitly file :Bitly File

It showing an error like below in the line as b is null

.GroupBy(b => b.Country)

enter image description here

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
Hrishikesh T T
  • 339
  • 2
  • 11
  • 3
    I think the exception is pretty self descriptive. You're trying to access a `null` value when you're grouping. This means that the JSON serializer is returning `null` for one of the entries inside your `.txt` file. Have you debugged the code? – Yuval Itzchakov Dec 02 '15 at 08:07
  • We accidently press an enter key inside .txt file . It causes the returning of null . – Hrishikesh T T Dec 03 '15 at 07:02

0 Answers0