如何将JSON映射到.NET类

Naz*_*med -1 c# asp.net api json web

我想将此JSON映射到.NET类.如何将此JSON数据映射到类中?请建议如何.这是json:

{"results": [
   "43853",
   "43855",
   "43856",
   "43857",
   {
     "questionType": 3,
     "choiceAnswers": [123]   
   }
 ]}
Run Code Online (Sandbox Code Playgroud)

Mar*_*und 5

最简单的解决方案是使用Visual Studio 编辑>选择性粘贴>将Json粘贴为类.但是因为你的json是一个不同对象的数组,.NET类就是这样

public class JsonDto
{
    public List<object> Results { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

使用对象列表会很痛苦,因此我建议您使用类型化模型,然后需要指定需要定义值,这是一个示例

{"results": [
     {
       "key1":"43853",
       "key2":"43855",
       "key3":"43856",
       "key4":"43857",
       "question": {
         "questionType": 3,
         "choiceAnswers": [123]   
       }
     }
 ]};

 public class JsonDto
 {
    public List<ResultDto> Results { get; set; }
 }
 public class ResultDto
 {
    public string Key1 { get; set; }
    public string Key2 { get; set; }
    public string Key3 { get; set; }
    public string Key4 { get; set; }
    public QuestionDto Question { get; set; }
 }
 public class QuestionDto
 {
    public int QuestionType { get; set; }
    public List<int> ChoiceAnswers { get; set; }
 }
Run Code Online (Sandbox Code Playgroud)