简体   繁体   English

如何将JSON映射到.NET类

[英]How can I map JSON to a .NET class

I want to map this JSON into a .NET class. 我想将此JSON映射到.NET类。 How can I map this JSON data into a class? 如何将JSON数据映射到类中? Please suggest how. 请提出建议。 Here is the json: 这是json:

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

The easiest solution is to use Visual Studio Edit > Paste Special > Paste Json As Classes . 最简单的解决方案是使用Visual Studio 编辑>选择性粘贴>将Json粘贴为类 But as your json is an array of different objects the .NET class will just be 但是由于您的json是不同对象的数组,因此.NET类将是

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

You can use online converter to convert json data to c# models http://json2csharp.com For your json it would be something like this. 您可以使用在线转换器将json数据转换为c#模型http://json2csharp.com对于您的json来说就是这样。

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

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

相关问题 如何通过验证将 JSON 正文属性映射为 .NET Core Web API 操作方法的动态参数? - How can I map JSON body properties as dynamic parameters of a .NET Core web API action method with validation? json.net:如何将“相似但不同”的外部json结构反序列化为单个类 - json.net: how can I deserialize 'similar but different' external json structures to a single class 如何在 C# ZA2F2ED4F8EBC2CBB4DZC2A 中使用 json.net 获取 json 中字段的唯一字段的值 - How can I get the value of the only field of a field in a json with json.net in a C# class 如何在网络 6 ZA2F2ED4F8EBC2CBB1DZ4 库中的 static class 中使用 appsettings.json - How can I use the appsettings.json in static class in net 6 class library 如何在FluentNHibernate中映射类? - How I can map class in FluentNHibernate? 如何将 Dapper QueryFirst 映射到类? - How can I map a Dapper QueryFirst to a class? 如何从统一反序列化json.net以获得多个/嵌套的类返回值? - How can I get multiple/nested class return values from deserializing json.net in unity? 如何将json映射到类模型? - How to map json to class models? 如何使用Json.Net反序列化? - How can I Deserialize with Json.Net? 我怎样用.net解析这个json? - How can i parse this json with .net?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM