将JSON转换为类,如何设置值

时间:2016-11-24 13:23:56

标签: c# json

我已将JSON粘贴到我的C#控制台应用程序中,因此它会生成如下类:

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; }
}

我希望设置identifierStringidentifierType的值,如下所示:

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

但是,我得到的对象引用未设置为对象的实例'错误。

2 个答案:

答案 0 :(得分:1)

你应该写:

 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";

甚至更好:

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

您缺少对象的创建,它们是空的

答案 1 :(得分:1)

或编译的版本:)

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