thatOneGuy thatOneGuy - 11 days ago 5
JSON Question

Converted JSON to classes, how to set values

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.

Answer

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

Comments