从父类实例化子对象

时间:2014-07-09 09:33:00

标签: c# .net json json.net

我试图从2个类使用JSON.Net生成一些JSON。以下是JSON的示例

{
  "UserToken" : "string",
  "MyProject" : 
  {
    "MyProjectId" : "string",
    "ProjectId" : "string",
    "ContactId" : "string",
    "DisplayOrder" : "int"
  }
}

这里是C#Classes

public class MyProject
{
    public string MyProjectId { get; set; }
    public string ProjectId { get; set; }
    public string ContactId { get; set; }
    public int DisplayOrder { get; set; }
}

public class RootObject
{
    public string UserToken { get; set; }
    public MyProject MyProject { get; set; }
}

你可以看到" RootObject"包含一个" MyProject"对象,但我无法解决如何实例化这个,所以我可以传递像:

这样的值
RootObject o = new RootObject();
o.MyProject.MyProjectId = "something";

我试过通过论坛搜索,但我得到的所有请求都是列表 - 我可以用它来解决问题,但我认为我的理解存在差距!

提前致谢, Ĵ

4 个答案:

答案 0 :(得分:2)

RootObject定义更改为

public class RootObject
{
     public RootObject() {
          this.MyProject = new MyProject();
     }
     public string UserToken { get; set; }
     public MyProject MyProject { get; set; }
}

或更改代码

RootObject o = new RootObject();
o.MyProject.MyProjectId = "something";

RootObject o = new RootObject();
o.MyProject = new MyProject();
o.MyProject.MyProjectId = "something";

代码的问题在于o.MyProject没有实例化。

答案 1 :(得分:0)

您正在创建父对象,但您还需要创建子对象,否则您将获得空引用异常。

RootObject o = new RootObject();
o.MyProject = new MyProject();   // <<<THIS
o.MyProject.MyProjectId = "something";

或者您可以像这样使用object initializer

RootObject o = new RootObject
{
    MyProject = new MyProject
    {
        MyProjectId = "something",
    }
};

答案 2 :(得分:0)

创建MyProject的对象,并将其分配给public MyProject类的RootObject()

RootObject o = new RootObject();
MyProject mp = new MyProject();
mp.MyProjectId = "something";
o.MyProject = mp;

答案 3 :(得分:0)

按如下方式更改您的代码。

public class MyProject
    {
        public MyProject()
        {
          this.MyProjectId =string.Empty;
          this.ProjectId =string.Empty;
          this.ContactId =string.Empty;
        }

        public string MyProjectId { get; set; }
        public string ProjectId { get; set; }
        public string ContactId { get; set; }
        public int DisplayOrder { get; set; }
    }

    public class RootObject
    {

        public RootObject()
        {
          this.MyProject =new MyProject ();
        }

        public string UserToken { get; set; }
        public MyProject MyProject { get; set; }
    }