-1

I have pasted JSON in to my C# console application, so it produces classes like so :

public class Rootobject
{
    public Id id { get; set; }
}

public class Id
{
    public Identifier Identifier { get; set; }
}

public class Identifier
{
    public Id1 id { get; set; }
    public Type type { get; set; }
}

public class Id1
{
    public string IdentifierString { get; set; }
}

public class Type
{
    public string IdentifierType { get; set; }
}

I wish to set the values of identifierString and identifierType like so :

var node = new Rootobject();
 node.id.Identifier.id.IdentifierString = "testId";
 node.id.Identifier.type.IdentifierType = "idType";

However, I get an 'Object reference not set to an instance of an object' error.

thatOneGuy
  • 9,977
  • 7
  • 48
  • 90
  • 1
    You need create other objects too: `node.Id = new Id();` – Fabio Nov 24 '16 at 13:26
  • The `Id` class is non-static. So, you need to create an object of it. – Atanu Roy Nov 24 '16 at 13:26
  • Possible duplicate of [Convert JSON String To C# Object](http://stackoverflow.com/questions/4611031/convert-json-string-to-c-sharp-object) – Liam Nov 24 '16 at 13:27
  • It's better to use a serilaizer for this kind of thing – Liam Nov 24 '16 at 13:28
  • Possible duplicate of [What does "Object reference not set to an instance of an object" mean?](http://stackoverflow.com/questions/779091/what-does-object-reference-not-set-to-an-instance-of-an-object-mean) – kiziu Nov 24 '16 at 13:53

2 Answers2

1

you should write:

 var node = new Rootobject();
 node.id = new Id();
 node.id.Identifier = new Identifier();
 node.id.Identifier.id = new Id1();
 node.id.Identifier.type = new Type();
 node.id.Identifier.id.IdentifierString = "testId";
 node.id.Identifier.type.IdentifierType = "idType";

or even better:

var node = new Rootobject
{
  id = new Id
  {
    Identifier = new Identifier
    {
      id = new Id1 { IdentifierString = "id" },
      type = new Type { IdentifierType = "type" },
    }
  }
};

You are missing creation of objects, they are nulls

thatOneGuy
  • 9,977
  • 7
  • 48
  • 90
Maksim Simkin
  • 9,561
  • 4
  • 36
  • 49
1

Or version which compile :)

var node = new RootObject
{
    id = new Id
    { 
        Identifier = new Identifier
        {
            id = new Id1 { IdentifierString = "id" },
            type = new Type { IdentifierType = "type" },
        }
    }
};
Fabio
  • 31,528
  • 4
  • 33
  • 72