简体   繁体   English

如何将JSON转换为C#类?

[英]How to convert JSON to C# classes?

I have a complex JSON object that I want represent as C# class. 我有一个复杂的JSON对象,我想表示为C#类。 I have a head start on the parent class called "Form", but how can I represent a collection for different types (see the "elements" object below)? 我在名为“Form”的父类上有一个良好的开端,但是我如何表示不同类型的集合(请参阅下面的“元素”对象)?

Here is the JSON object: 这是JSON对象:

{
    "action": "index.html",
    "method": "post",
    "elements":
[
{
    "type": "fieldset",
    "caption": "User information",
    "elements":
    [
        {
            "name": "email",
            "caption": "Email address",
            "type": "text",
            "placeholder": "E.g. user@example.com",
            "validate":
            {
                "email": true
            }
        },
        {
            "name": "password",
            "caption": "Password",
            "type": "password",
            "id": "registration-password",
            "validate":
            {
                "required": true,
                "minlength": 5,
                "messages":
                {
                    "required": "Please enter a password",
                    "minlength": "At least {0} characters long"
                }
            }
        },
        {
            "name": "password-repeat",
            "caption": "Repeat password",
            "type": "password",
            "validate":
            {
                "equalTo": "#registration-password",
                "messages":
                {
                    "equalTo": "Please repeat your password"
                }
            }
        },
        {
            "type": "radiobuttons",
            "caption": "Sex",
            "name": "sex",
            "class": "labellist",
            "options":
            {
                "f": "Female",
                "m": "Male"
            }
        }
    ]
]
}

The class I have start looks like this: 我开始上课的时间如下:

public class Form
{
    public Guid id
    {
        get;
        set;
    }

    public string action
    {
        get;
        set;
    }

    public string method
    {
        get;
        set;
    }

    public ??? elements
    {
        get;
        set;
    }

    public Form()
    {

    }
}

How do I handle the "elements" property to get the desired JSON output? 如何处理“elements”属性以获得所需的JSON输出?

I am using WCF 4.0 with these atributes in the web.config: automaticFormatSelectionEnabled="false", defaultOutgoingResponseFormat="Json". 我在web.config中使用WCF 4.0和这些属性:automaticFormatSelectionEnabled =“false”,defaultOutgoingResponseFormat =“Json”。 Any help or ideas would be greatly appreciated. 任何帮助或想法将不胜感激。

If you don't have the liberty of using dynamic types from .NET 4 or would like to leverage the benefits that static typing provide, the JSON Class Generator project on codeplex will generate c# classes given a json input string. 如果您不能自由使用.NET 4中的动态类型或想利用静态类型提供的好处,则codeplex上的JSON Class Generator项目将在给定json输入字符串的情况下生成c#类。 (shameless plug) I've also taken code from this project and slapped a web UI on it . (无耻的插件)我还从这个项目中获取了代码并在其上打了一个Web UI

Wow. 哇。 Fascinating question. 引人入胜的问题。 Maybe use ExpandoObject / dynamic? 也许使用ExpandoObject / dynamic?

http://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject.aspx http://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject.aspx

http://blogs.msdn.com/b/csharpfaq/archive/2009/10/01/dynamic-in-c-4-0-introducing-the-expandoobject.aspx?PageIndex=4 http://blogs.msdn.com/b/csharpfaq/archive/2009/10/01/dynamic-in-c-4-0-introducing-the-expandoobject.aspx?PageIndex=4

Or anonymous types I think are serializable with the built-in .NET JSON serializer. 或者我认为匿名类型可以使用内置的.NET JSON序列化程序进行序列化。

If you just want to make sure all this unknown data gets deserialized and can be reserialized at some point in the future, I suggest the usage of IExtensibleDataObject. 如果您只是想确保所有这些未知数据被反序列化并且可以在将来某个时候重新序列化,我建议使用IExtensibleDataObject。

Here are some samples to get you started. 以下是一些可以帮助您入门的示例。 Hope this helps! 希望这可以帮助! (If you already knew this and were looking for something different...let me know!) (如果你已经知道这一点并且正在寻找不同的东西......请告诉我!)

Forward-Compatible Data Contracts 前向兼容数据合同

Data Contract Versioning 数据合同版本控制

Useful clarifying thread on the topic at MSDN forums 在MSDN论坛上有关该主题的有用澄清线程

You do not need to try and create the class structure manually. 您无需手动尝试创建类结构。

Sometimes it is rather frustrating too. 有时它也相当令人沮丧。 :) :)

There is a visual studio command you can use (I think vs2015 and later): 你可以使用一个visual studio命令 (我认为vs2015及更高版本):

  1. On a new class file click Menu => Edit => Paste Special 在新的类文件上,单击Menu => Edit => Paste Special
  2. Select "Paste JSON as Classes" 选择“将JSON粘贴为类”

Now specifically in your JSON there is an error, you are missing the closing curly-brace of first "element" object. 现在特别在你的JSON中有一个错误,你缺少第一个“元素”对象的结束花括号。

Below is the corrected JSON: 以下是更正后的JSON:

{
  "action": "index.html",
  "method": "post",
  "elements": [
    {
      "type": "fieldset",
      "caption": "User information",
      "elements": [
        {
          "name": "email",
          "caption": "Email address",
          "type": "text",
          "placeholder": "E.g. user@example.com",
          "validate": {
            "email": true
          }
        },
        {
          "name": "password",
          "caption": "Password",
          "type": "password",
          "id": "registration-password",
          "validate": {
            "required": true,
            "minlength": 5,
            "messages": {
              "required": "Please enter a password",
              "minlength": "At least {0} characters long"
            }
          }
        },
        {
          "name": "password-repeat",
          "caption": "Repeat password",
          "type": "password",
          "validate": {
            "equalTo": "#registration-password",
            "messages": {
              "equalTo": "Please repeat your password"
            }
          }
        },
        {
          "type": "radiobuttons",
          "caption": "Sex",
          "name": "sex",
          "class": "labellist",
          "options": {
            "f": "Female",
            "m": "Male"
          }
        }
      ]
    }
  ]
}

And the corresponding Classes: 和相应的类:

public class Rootobject
{
    public string action { get; set; }
    public string method { get; set; }
    public Element[] elements { get; set; }
}

public class Element
{
    public string type { get; set; }
    public string caption { get; set; }
    public Element1[] elements { get; set; }
}

public class Element1
{
    public string name { get; set; }
    public string caption { get; set; }
    public string type { get; set; }
    public string placeholder { get; set; }
    public Validate validate { get; set; }
    public string id { get; set; }
    public string _class { get; set; }
    public Options options { get; set; }
}

public class Validate
{
    public bool email { get; set; }
    public bool required { get; set; }
    public int minlength { get; set; }
    public Messages messages { get; set; }
    public string equalTo { get; set; }
}

public class Messages
{
    public string required { get; set; }
    public string minlength { get; set; }
    public string equalTo { get; set; }
}

public class Options
{
    public string f { get; set; }
    public string m { get; set; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM