Search code examples
c#jsonnew-operatornullreferenceexception

Create new JSON item in an array


I'm setting my first steps in C# and JSON.

I've installed Web Essentials in my Visual Studio environment, and I've used it to create a JSON class structure.

My JSON looks as follows:

{
    "project": {
        "common.DESCRIPTION": "Project_Description",
        ...
        "locations": [
            {
                "common.NAME": "Location_Name",
                ...

The Web Essentials "Paste Special" (for creating the classes out of the JSON) generated something like:

public class Project
{
    public string commonDESCRIPTION { get; set; }
    ...
    public Location[] locations { get; set; }
    ...
}

public class Location
{
    public string commonNAME { get; set; }
    ...

My code looks as follows:

Rootobject root = new Rootobject();
for (int i = 0; i < listbox_with_names.Items.Count; i++)
{
    root.project = new Project();
    root.project.locations[i] = new Location();
    root.project.locations[i].commonNAME = listbox_with_names.Items[i].ToString();

This code fails because the locations have null value, causing a NullPointerException.
However, root and project seem to be fine.

Apparently, I'm doing something wrong in this line:

root.project.locations[i] = new Location();

Does anybody know how to declare an object, which is to be a part of an array, in C#? (Or am I completely wrong using the new operator as I've done for root and project?)

P.S. there is the comment that my question is a duplicate of another post, but this post is extremely large and it's extremely difficult to find back the one issue I'm dealing with (if it's even mentioned there, I had a look and I felt like "TL;DR" (too long, didn't read), sorry).


Solution

  • Thanks to Peter B and some debugging, I found the solution: 2 individual constructors need to be run as you can see:

    Rootobject root = new Rootobject();
    root.project = new Project();
    root.project.locations = new Location[listbox_with_names.Items.Count]; // construct the array
    for (int i = 0; i < listbox_with_names.Items.Count; i++)
    {
        root.project.locations[i] = new Location(); // construct each array member separately