1

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).

2
  • root.project.locations = new Location[0];, More information in the official documentation : learn.microsoft.com/en-us/dotnet/csharp/programming-guide/… Commented Jun 10, 2021 at 8:37
  • Use this to initialize locations, it does not happen by itself: root.project = new Project { locations = new Location[numberOfLocations] }. You need to determine the value for numberOfLocations from somewhere, and it must be at least 1 or else the array can't store any items. Commented Jun 10, 2021 at 8:39

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.