【问题标题】:How can I map JSON to a .NET class如何将 JSON 映射到 .NET 类
【发布时间】:2018-05-03 08:26:06
【问题描述】:

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

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

【问题讨论】:

  • 请不要将 JSON 放在您的问题标题中。它真的不需要,也不应该在这里。另外,您是说需要创建相应的模型,还是需要知道如何反序列化?这可能很棘手,因为在您的示例中,字符串和对象在单个数组中是不同的类型。
  • 我需要模型
  • 在 Visual Studio 中,转到 Edit > Paste Special > Paste Json As Classes
  • 您可以根据给定的 JSON 创建 Dto,并使用 Newtonsoft 等外部库将 Json 与 Dto 映射。
  • @CodeNotFound 你能做到吗?甜蜜。

标签: c# asp.net json api web


【解决方案1】:

您可以使用在线转换器将 json 数据转换为 c# 模型http://json2csharp.com 对于您的 json,它将是这样的。

public class RootObject
{
    public List<object> results { get; set; }
}

【讨论】:

  • 我最初的查询是对象类将如何。
  • 因为您不能拥有 Marcus 定义的固定类。对于您的方案,对象列表是最佳选择。装箱和拆箱也将出现。
【解决方案2】:

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

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

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

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

【讨论】:

  • 但我不需要密钥。我只需要像“41254”、“45465”这样的键值。而且键的数量不固定,它可以有更多的值,比如 key5、key6、key 7好吧。
  • @NazimAhmed 然后你应该使用一个字符串列表, List Keys { get;放; }
  • @ Marcus Hoglund 但是当我使用字符串列表时,keys 属性正在接收空值。我无法更改 json,但我必须以准确的格式将其映射到我的班级。
  • @NazimAhmed 如果您无法更改 json 模型,那么您必须使用 List 结果
  • @Marcus Hoglund 我不能使用 JObject,因为我的项目在 vs2012 中,所以我无法安装 newtonsoft.json。所以它不受支持。我必须以另一种方式解析它,而不是 List
猜你喜欢
  • 2015-08-01
  • 2016-10-22
  • 2018-06-19
  • 2013-06-16
  • 2016-04-29
  • 2017-12-24
  • 2022-08-11
  • 2011-08-09
  • 1970-01-01
相关资源
最近更新 更多