0

Whenever I try to get the list of items in NewtownSoft json with c# I get this exception "System.NullReferenceException" I don't know how to resolve this ,I tried my best but still getting this exception. Here is the code and output.

public object Retrive(String FileName, Type DataType)
    {
        JObject obj = new JObject();
        obj = null;
        try
        {
            if (!File.Exists(CreateConfigutionFilePath(FileName)))
            {
                _ = File.Create(CreateConfigutionFilePath(FileName));
                return obj;
            }
            if (new FileInfo(CreateConfigutionFilePath(FileName)).Length != 0)
            {
                JsonSerializer jsonSerializer = new JsonSerializer();
                using (StreamReader textReader = new StreamReader(CreateConfigutionFilePath(FileName)))
                {
                    JsonReader jsonReader = new JsonTextReader(textReader);
                    obj = jsonSerializer.Deserialize(jsonReader) as JObject;
                }
            }

        }
        catch (Exception e)
        {
            // TODO TO Add A PRompt
            Console.WriteLine(e);
        }
        object DataObject = obj.ToObject(DataType);
        return DataObject;
    }

Output:

Exception thrown: 'System.NullReferenceException' in IMS.exe System.NullReferenceException: Object reference not set to an instance of an object. at IMS.Helpers.SettingHelper.Retrive(String FileName, Type DataType) in D:\ME\Visual Studio Projects\IMS\IMS\Helpers\SettingHelper.cs:line 168 at IMS.Pages.SettingsPages.InstituteSettings.RetriveConfig() in D:\ME\Visual Studio Projects\IMS\IMS\Page

  • Have you tried debugging your code? Which line does it fail on? This line will throw if it's not entered the second if statement `object DataObject = obj.ToObject(DataType);`. Why don't you store the file path in a variable rather than calling the mysterious `CreateConfigutionFilePath` multiple times? – haldo Feb 15 '22 at 12:00
  • Are you sure that the file you're trying to read exists? By calling File.Create you're creating an *empty* file, and, most probably, you will get NullRef exceptions because empty file deserializing gives you either null, or the object with all fields and properties null/initialized Also you can use typed deserialization directly and turn your function into generic one – HaroldMorgan Feb 15 '22 at 13:09
  • Since the question is "how to retrieve list": Maybe you forgot to create a list of objects? You can try this: `var myList = JsonConvert.DeserializeObject>(File.ReadAllText(FileName));` – tomwaitforitmy Feb 15 '22 at 13:31
  • 1
    Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – haldo Feb 15 '22 at 13:57

0 Answers0