将 JSON 字符串反序列化为 .NET 对象

问题描述 投票:0回答:1

我有一个如下所示的 JSON 字符串:

[
  {
    "movie title": "The Matrix",
    "release date": "1999-03-31",
    "movie rating": 8.7,
    "main actor": {
      "name": "Keanu Reeves",
      "age": 57,
      "gender": "Male"
    },
    "seen": true
  },
  {
    "movie title": "Inception",
    "release date": "2010-07-16",
    "movie rating": 8.8,
    "main actor": {
      "name": "Leonardo DiCaprio",
      "age": 47,
      "gender": "Male"
    },
    "seen": false
  }
]

我需要将上面的JSON字符串转换为.NET对象类型。

注意: JSON 名称无法更改,因为它来自使用 webapi 调用的 Excel 文档,将 Excel 数据转换为 JSON 类型。

将上述 JSON 字符串转换为 .NET 对象时遇到转换错误。 请帮我解决上述问题?预先感谢。

json .net json-deserialization jsonserializer
1个回答
0
投票

需要如下 2 个自定义类。

public class MainActor
{
    public string name { get; set; }
    public int age { get; set; }
    public string gender { get; set; }
}

public class Root
{
    [JsonProperty("movie title")]
    public string movietitle { get; set; }

    [JsonProperty("release date")]
    public string releasedate { get; set; }

    [JsonProperty("movie rating")]
    public double movierating { get; set; }

    [JsonProperty("main actor")]
    public MainActor mainactor { get; set; }
    public bool seen { get; set; }
}

现在,从 json 字符串创建 C# 对象。执行下面的操作。

    var jsonSting = @"[
 {
 "movie title": "The Matrix",
 "release date": "1999-03-31",
 "movie rating": 8.7,
 "main actor": {
  "name": "Keanu Reeves",
  "age": 57,
  "gender": "Male"
 },
 "seen": true
},
{
"movie title": "Inception",
"release date": "2010-07-16",
"movie rating": 8.8,
"main actor": {
  "name": "Leonardo DiCaprio",
  "age": 47,
  "gender": "Male"
},
"seen": false
}
]";
var myObject = JsonConvert.DeserializeObject<List<Root>>(jsonString);

虽然代码尚未测试,但应该可以工作。

© www.soinside.com 2019 - 2024. All rights reserved.