1

I am unable to deserialize JSON objects from file for some reason, even tho it works from a variable created within the code itself. But when I switch it out for another path to my json-file instead; it says “An exception of type 'System.NullReferenceException' occurred in jsonParseTest.dll but was not handled in user code

Additional information: Object reference not set to an instance of an object.” And points at listOfCustomers.data.

It clearly locates the json-file but is unable to deserialize it for some reason. What could be the issue? Image of code

Mikael
  • 39
  • 4
  • See http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it – Kalten Mar 20 '16 at 17:38

1 Answers1

1

I can see that your commented out json in line #16, starts with a object called data, and the value for that key is the json within an array. And you are trying to iterate within the “listOfCustomers.data”, but when you are serializing you are simply creating a Customer object and passing that as a parameter to jsonConvert.SerializeObject()-method.

You need to create a new Customer List and add the customer-object into that freshly created Customer List-key named “data” as a list of the type Customer. After that you could try to serialize the newly created customer list which consists of a list of the type customer.

Customer customer = new Customer { id = “234234”, name = “Mikael” };
CustomerList customerList = new CustomerList { data = new List<Customer> { customer } };
string outputJSON = JsonConvert.SerializeObject(customerList);
System.IO.File.WriteAllText(outputPath, outputJSON);

Also I can see that you are using two different classes for serialization and deserialization as of line # 23.

Instead of using the JavaScriptSerializer which is a part of the .net-framework, you could simply use the JsonConvert.DeserializeObject-method since you are already using other methods from the JsonConvert-class.

CustomerList listOfCustomers = JsonConvert.DeserializeObject<CustomerList>(json);

Here we are using the JsonConvert.DeserializeObject-method and passing in a CustomerList-type.

Anders Gill
  • 305
  • 1
  • 6