【问题标题】:How do I represent this complex json document as a C# object?如何将这个复杂的 json 文档表示为 C# 对象?
【发布时间】:2013-06-27 13:10:48
【问题描述】:

我想创建一个 C# 基对象类,它代表下面的 Json 文档(这是一个调查表)。我可以轻松地完成前三三行,但我如何从 "FormBody": { } 在病房中进行嵌套。

我看到人们在哪里使用public IDictionary<string, object> FormBody {get; set;}。我可以将它传递给 Json.Net 并让它为我填充对象类吗?还是有其他方法?

{
  "FormTitle": "Product 27",
  "FormId": "CCC12345",
  "Type": "forms",
  "FormBody": {
    "image": {
      "width": 450,
      "height": 200,
      "title": "ACME Insurance",
      "location": "Images/Forms/sample.jpg"
    },
    "heading1": {
      "text": "Commercial Crime"
    },
    "body1": {
      "text": "Important Notice, It is important that you as the proposer provide full and detailed answers to all the questions to enable the insurer to properly assess the risk involved and that the quote will be fair"
    },
    "heading2": {
      "text": "How to use this form"
    },
    "body2": {
      "text": "Please answer the questions listed below by either selecting an answer from the provided list/ contorl or enter the information into the designated field"
    },
    "categories": [
      {
        "name": "Gerenal Information",
        "questions": [
          {
            "questionNumber": "1",
            "dependencyLevel": {
              "question": "0",
              "answer": "0"
            },
            "questionText": "Are there any subsidiary companies that need to be included?",
            "answerOptions": {
              "control": {
                "type": "groupCheckBox",
                "selectionOptions": {
                  "availibleSelectionAmount": "2",
                  "options": [
                    "Yes",
                    "No"
                  ]
                }
              }
            },
            "selectedAnswer": {
              "selection": "Yes"
            }
          },
          {
            "questionNumber": "1.1",
            "dependencyLevel": {
              "question": "1",
              "answer": "Yes"
            },
            "questionText": "How many subsidiaries need to be included?",
            "questionInformation": {
              "text": "Please enter a number"
            },
            "answerOptions": {
              "control": {
                "type": "dropDownList",
                "selectionOptions": {
                  "availibleSelectionAmount": "5",
                  "options": [
                    "1",
                    "2",
                    "3",
                    "4",
                    "5"
                  ]
                }
              }
            },
            "selectedAnswer": {
              "selection": "1"
            }
          },
          {
            "questionNumber": "1.2",
            "dependencyLevel": {
              "question": "1",
              "answer": "Yes"
            },
            "questionText": "Does the proposer have branches, subsidiaries, entities which are based outside RSA?",
            "questionInformation": {
              "text": "Please select one of the following"
            },
            "answerOptions": {
              "control": {
                "type": "groupCheckBox",
                "selectionOptions": {
                  "availibleSelectionAmount": "2",
                  "options": [
                    "Yes",
                    "No"
                  ]
                }
              }
            },
            "selectedAnswer": {
              "selection": "No"
            }
          }
        ]
      },
      {
        "name": "HR",
        "questions": [
          {
            "questionNumber": "2",
            "dependencyLevel": {
              "question": "0",
              "answer": "0"
            },
            "questionText": "How often does someone who is not normally involved in the payroll's update and preperation check on the payroll?",
            "questionInformation": {
              "text": "Please select one from the list"
            },
            "answerOptions": {
              "control": {
                "type": "dropDownList",
                "selectionOptions": {
                  "availibleSelectionAmount": "5",
                  "options": [
                    "At least ounce a month",
                    "At least ounce a quater",
                    "At least every 6 months",
                    "Less than ounce a month",
                    "Less often"
                  ]
                }
              }
            },
            "selectedAnswer": {
              "selection": "At least ounce a month"
            }
          }
        ]
      },
      {
        "name": "Accounting",
        "information": "An owner/manger is an individual who owns most of the proposers shares and runs the business",
        "questions": [
          {
            "questionNumber": "3",
            "dependencyLevel": {
              "question": "0",
              "answer": "0"
            },
            "questionText": "Does the proposer's processes allow for someone to make payments without the owner/manager's knowledge",
            "questionInformation": {
              "text": "Please select one from the list"
            },
            "answerOptions": {
              "control": {
                "type": "dropDownList",
                "selectionOptions": {
                  "availibleSelectionAmount": "5",
                  "options": [
                    "At least ounce a month",
                    "At least ounce a quater",
                    "At least every 6 months",
                    "Less than ounce a month",
                    "Less often"
                  ]
                }
              }
            },
            "selectedAnswer": {
              "selection": "At least ounce a month"
            }
          },
          {
            "questionNumber": "3.1",
            "dependencyLevel": {
              "question": "3",
              "answer": "2"
            },
            "questionText": "Is dual authority required for EFTs?",
            "questionInformation": {
              "text": "Please select one"
            },
            "answerOptions": {
              "control": {
                "type": "checkBox",
                "selectionOptions": {
                  "availibleSelectionAmount": "2",
                  "options": [
                    "Yes",
                    "No"
                  ]
                }
              }
            },
            "selectedAnswer": {
              "selection": "Yes"
            }
          },
          {
            "questionNumber": "3.2",
            "dependencyLevel": {
              "question": "3.1",
              "answer": "Yes"
            },
            "questionText": "Are the people loading and releasing the payments both to check that the payments are made against a suitible authorisation document(e.g. signed purchase order, delivery note or similar)?",
            "questionInformation": {
              "text": "Please select one"
            },
            "answerOptions": {
              "control": {
                "type": "checkBox",
                "selectionOptions": {
                  "availibleSelectionAmount": "2",
                  "options": [
                    "Yes",
                    "No"
                  ]
                }
              }
            },
            "selectedAnswer": {
              "selection": "Yes"
            }
          },
          {
            "questionNumber": "4",
            "dependencyLevel": {
              "question": "0",
              "answer": "0"
            },
            "questionText": "Does the proposer have an annual formal budgeting process and is management approval required for payments which fall outside the budget?",
            "questionInformation": {
              "text": "Please select one from the list"
            },
            "answerOptions": {
              "control": {
                "type": "dropDownList",
                "selectionOptions": {
                  "availibleSelectionAmount": "4",
                  "options": [
                    "No formal budget",
                    "Yes, there is a budget but it is a guideline only and is not strictly enforced",
                    "Yes, there is a formal budget and any deviations require managemant approval",
                    "Yes, there is a formal budget but small purchases outside the budget do not require management approval"
                  ]
                }
              }
            },
            "selectedAnswer": {
              "selection": "Yes, there is a formal budget and any deviations require managemant approval"
            }
          }
        ]
      },
      {
        "name": "Cash",
        "questons": [
          {
            "questionNumber": "5",
            "dependencyLevel": {
              "question": "0",
              "answer": "0"
            },
            "questionText": "What is the typical maximum amount of cash and near cash on hand at any one time? This includes petty cash, payments by debtors, creditor's payments, etc. Near cash includes coins and negotiables such as cheques, etc.",
            "questionInformation": {
              "text": "Please select one from the list"
            },
            "answerOptions": {
              "control": {
                "type": "dropDownList",
                "selectionOptions": {
                  "availibleSelectionAmount": "5",
                  "options": [
                    "Less than R 50,000",
                    "Less than R 100,000",
                    "Less than R 250,000",
                    "Less than R 2,500,000",
                    "More than R 2,500,000"
                  ]
                }
              }
            },
            "selectedAnswer": {
              "selection": "More than R 2,500,000"
            }
          },
          {
            "questionNumber": "5.1",
            "dependencyLevel": {
              "question": "5",
              "answer": "More than R 2,500,000"
            },
            "questionText": "Is the proposer paid in cash for goods/services?",
            "questionInformation": {
              "text": "Please select one from the list"
            },
            "answerOptions": {
              "control": {
                "type": "dropDownList",
                "selectionOptions": {
                  "availibleSelectionAmount": "5",
                  "options": [
                    "Never",
                    "Less than once a month",
                    "Somethimes",
                    "Often",
                    "Very Often"
                  ]
                }
              }
            },
            "selectedAnswer": {
              "selection": "Very Often"
            }
          },
          {
            "questionNumber": "5.1.1",
            "dependencyLevel": {
              "question": "5.1",
              "answer": "4"
            },
            "questionText": "How often are cash reconciliations done?",
            "questionInformation": {
              "text": "Please select one from the list"
            },
            "answerOptions": {
              "control": {
                "type": "dropDownList",
                "selectionOptions": {
                  "availibleSelectionAmount": "5",
                  "options": [
                    "Never",
                    "Less than once a month",
                    "Somethimes",
                    "Often",
                    "Very Often"
                  ]
                }
              }
            },
            "selectedAnswer": {
              "selection": "Often"
            }
          }
        ]
      }
    ]
  }
}

【问题讨论】:

    标签: c# json object json.net


    【解决方案1】:
    [DataContract]
    public sealed class MyJson
    {
        [DataMember(Name="FormTitle", IsRequired = true)]
        public string FormTitle { get; set; }
    
        ...
    
        [DataMember(Name="FormBody", IsRequired = true)]
        public FormBody fb { get; set; }
    }
    
    [DataContract]
    public sealed class FormBody
    {
        [DataMember(Name="image", IsRequired = true)]
        public Image img { get; set; }
    
        ...
    }
    

    等等等等。您可以为您的 JSon 中的每个复杂类型创建一个类(可以直接使用 Strings 和 String[])。

    如何序列化:

    var jsonString = ...
    
    var json = new DataContractJsonSerializer (typeof(MyJson));
    var stream = new MemoryStream (System.Text.Encoding.UTF8.GetBytes (jsonString));
    var myObj = (MyJson)json.ReadObject (stream);
    stream.Close ();
    

    如何反序列化:

    FileStream fileStream = System.IO.File.Create (filepath);
    
    MemoryStream stream = new MemoryStream ();
    DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer (typeof(MyJson));
    
    jsonSerializer.WriteObject (stream, myObj);
    stream.Position = 0;
    StreamReader sr = new StreamReader (stream);
    
    string jsonString = sr.ReadToEnd ();
    

    【讨论】:

    • 啊,使用的命名空间是System.Runtime.Serialization
    • 那么您将如何完成我在答案中列出的课程?
    • 我向你展示了开头 - 字符串 FormTitleFormIdType 作为“主”类的字段,然后是复杂类型 FormBody(单独的类),包括 - @ 987654329@,body1heading2body2,每个都包含String text作为唯一的字段-这意味着您可以创建一个类并将其用作所有四个的类型...我希望我自己清楚.. 仔细查看您的 json,您将看到如何对其进行建模。但是不要指望其他人会为您编写代码:)
    • 我完全不希望这样,但非常感谢您的帮助
    【解决方案2】:

    我刚刚发现这个website 为您创建了对象类,但它们是否正确?

    public class Image
    {
        public int width { get; set; }
        public int height { get; set; }
        public string title { get; set; }
        public string location { get; set; }
    }
    
    public class Heading1
    {
        public string text { get; set; }
    }
    
    public class Body1
    {
        public string text { get; set; }
    }
    
    public class Heading2
    {
        public string text { get; set; }
    }
    
    public class Body2
    {
        public string text { get; set; }
    }
    
    public class DependencyLevel
    {
        public string question { get; set; }
        public string answer { get; set; }
    }
    
    public class SelectionOptions
    {
        public string availibleSelectionAmount { get; set; }
        public List<string> options { get; set; }
    }
    
    public class Control
    {
        public string type { get; set; }
        public SelectionOptions selectionOptions { get; set; }
    }
    
    public class AnswerOptions
    {
        public Control control { get; set; }
    }
    
    public class SelectedAnswer
    {
        public string selection { get; set; }
    }
    
    public class QuestionInformation
    {
        public string text { get; set; }
    }
    
    public class Question
    {
        public string questionNumber { get; set; }
        public DependencyLevel dependencyLevel { get; set; }
        public string questionText { get; set; }
        public AnswerOptions answerOptions { get; set; }
        public SelectedAnswer selectedAnswer { get; set; }
        public QuestionInformation questionInformation { get; set; }
    }
    
    public class DependencyLevel2
    {
        public string question { get; set; }
        public string answer { get; set; }
    }
    
    public class QuestionInformation2
    {
        public string text { get; set; }
    }
    
    public class SelectionOptions2
    {
        public string availibleSelectionAmount { get; set; }
        public List<string> options { get; set; }
    }
    
    public class Control2
    {
        public string type { get; set; }
        public SelectionOptions2 selectionOptions { get; set; }
    }
    
    public class AnswerOptions2
    {
        public Control2 control { get; set; }
    }
    
    public class SelectedAnswer2
    {
        public string selection { get; set; }
    }
    
    public class Queston
    {
        public string questionNumber { get; set; }
        public DependencyLevel2 dependencyLevel { get; set; }
        public string questionText { get; set; }
        public QuestionInformation2 questionInformation { get; set; }
        public AnswerOptions2 answerOptions { get; set; }
        public SelectedAnswer2 selectedAnswer { get; set; }
    }
    
    public class Category
    {
        public string name { get; set; }
        public List<Question> questions { get; set; }
        public string information { get; set; }
        public List<Queston> questons { get; set; }
    }
    
    public class FormBody
    {
        public Image image { get; set; }
        public Heading1 heading1 { get; set; }
        public Body1 body1 { get; set; }
        public Heading2 heading2 { get; set; }
        public Body2 body2 { get; set; }
        public List<Category> categories { get; set; }
    }
    
    public class RootObject
    {
        public string FormTitle { get; set; }
        public string FormId { get; set; }
        public string Type { get; set; }
        public FormBody FormBody { get; set; }
    }
    

    【讨论】:

    • 是的,看起来是正确的。您的 JSON 只是其他对象中的一堆对象。要将其转换为 c#,您必须声明类,以便您可以从另一个对象引用该类型的对象。
    • 好的,我明白你在说什么,所以标题 1 是表单正文的一种类型?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多