以编程方式进行Json.Net Serialization

gio*_*efj 0 c# serialization json

我必须将一些信息序列化为json,然后将它们写入文件.实际上我想要达到的结果是:

{
  "Email": "james@example.com",
  "Active": true,
  "CreatedDate": "2013-01-20T00:00:00Z",
  "libraries": [
    {
      "name": "name1"
    },
    {
      "name": "name2"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

这是我用来存储信息的类:

public class JSON
{
    public string Email { get; set; }
    public bool Active { get; set; }
    public DateTime CreatedDate { get; set; }
    public string[] libraries { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后我用它来序列化它们:

JSON account = new JSON
{
    Email = "james@example.com",
    Active = true,
    CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc),
    libraries = new[] {"Small","Medium","Large" }

};

string json = JsonConvert.SerializeObject(account, Formatting.Indented);
Run Code Online (Sandbox Code Playgroud)

问题是,实际上我得到的结果是这样的:

{
  "Email": "james@example.com",
  "Active": true,
  "CreatedDate": "2013-01-20T00:00:00Z",
  "libraries": [
    "Small",
    "Medium",
    "Large"
  ]
}
Run Code Online (Sandbox Code Playgroud)

我怎么解决呢?

Ant*_*kov 5

将您的JSON类更改为此类:

public class Library
{
    public string name { get; set; }
}

public class JSON
{
    public string Email { get; set; }
    public bool Active { get; set; }
    public string CreatedDate { get; set; }
    public List<Library> libraries { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

如何使用在线工具生成类

好的提示是使用JSON到C#转换器,它将生成C#类.

如何使用Visual Studio生成类

其他选项是使用内置的Visual Studio功能(适用于VS2013及更高版本).

如果您在剪贴板中有JSON文件,则可以:

编辑 - >选择性粘贴 - >将JSON粘贴为类

如何使用新课程

JSON account = new JSON
{
    Email = "james@example.com",
    Active = true,
    CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc),
    libraries = new List<Library>  
            {
              new Library {name = "Small"},
              new Library {name = "Medium"},
              new Library {name = "Large"} 
            }

};
Run Code Online (Sandbox Code Playgroud)