【问题标题】:C# parse array inside JSON [duplicate]C#解析JSON内的数组[重复]
【发布时间】:2017-06-15 20:53:35
【问题描述】:

我有这个 JSON:

{
   "Date": "3/6/17",
   "Place": "MyPlace",
   "Questions": [{
       "Category": "",
       "Question": "???",
       "Answer": ""
   }, {
       "Category": "",
       "Question": "??? ",
       "Answer": ""
   }, {
       "Category": "",
       "Question": "???",
       "Answer": ""
   }]
}

我想解析这个 JSON 并将其中的数组作为列表获取。
使用var list = JsonConvert.DeserializeObject<List<JToken>>(jsonString); 不起作用,因为整个事物不是一个数组,只有它里面有一个数组。
那么如何在 C# 中做到这一点?

【问题讨论】:

  • 创建一些与您的模型匹配的 C# 类,并反序列化为这些类。
  • @Amy 你能给我举个例子吗?
  • @amitairos 有 很多 的例子。 Newtonsoft 文档有很多。

标签: c# arrays json json.net


【解决方案1】:

您可以定义以下类:

public class Question
{

    [JsonProperty("Category")]
    public string Category { get; set; }

    [JsonProperty("Question")]
    public string Question { get; set; }

    [JsonProperty("Answer")]
    public string Answer { get; set; }
}

public class QuestionsDatePlace
{
    [JsonProperty("Date")]
    public string Date { get; set; }

    [JsonProperty("Place")]
    public string Place { get; set; }

    [JsonProperty("Questions")]
    public IList<Question> Questions { get; set; }
}

然后反序列化您的 json,如下所示:

var list = JsonConvert.DeserializeObject<QuestionsDatePlace>(jsonString);

【讨论】:

    【解决方案2】:

    最简单的方法,无需创建额外的类:

    dynamic json = new JavaScriptSerializer().Deserialize<dynamic>(jsonString);
    var list = json["Questions"];
    

    如果您需要将结果转换为 JToken 对象序列,请执行此操作。

    dynamic json = new JavaScriptSerializer().Deserialize<dynamic>(jsonString);
    var list = ((IEnumerable<dynamic>)json["Questions"]).Select(q => new JToken()
    {
        Category = q["Category"],
        Question = q["Question"],
        Answer = q["Answer"]
    });
    

    为了记录,这需要在Solution ExplorerReferences 节点中添加程序集System.Web.Extensions

    【讨论】:

      猜你喜欢
      • 2016-03-28
      • 2016-12-14
      • 2016-04-21
      • 2013-03-25
      • 1970-01-01
      • 1970-01-01
      • 2023-04-11
      • 2020-09-30
      • 2016-05-08
      相关资源
      最近更新 更多