如何将JSON映射到.NET类 [英] How can I map JSON to a .NET class

查看:161
本文介绍了如何将JSON映射到.NET类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to map this JSON into a .NET class. How can I map this JSON data into a class? Please suggest how. Here is the json:

{"results": [
   "43853",
   "43855",
   "43856",
   "43857",
   {
     "questionType": 3,
     "choiceAnswers": [123]   
   }
 ]}

推荐答案

最简单的解决方案是使用Visual Studio 编辑>选择性粘贴>将Json粘贴为类. 但是由于您的json是不同对象的数组,因此.NET类将只是

The easiest solution is to use Visual Studio Edit > Paste Special > Paste Json As Classes. But as your json is an array of different objects the .NET class will just be

public class JsonDto
{
    public List<object> Results { get; set; }
}

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

A list of objects will be painful to work with so I recommend that you to use a typed model but then you need to specify you need to define the values, here's an example

{"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; }
 }

这篇关于如何将JSON映射到.NET类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆