【问题标题】:Create several tables in a single Json without using JArray?在一个 Json 中创建多个表而不使用 JArray?
【发布时间】:2018-08-30 07:06:50
【问题描述】:

我正在开发一个 IMDB 类型的程序,在该程序中我列出了拥有电影、唱片和类似作品的人。所以我已经在 MVVM 中提出了自己的观点,现在我正在尝试序列化我的 json 以匹配它。现在我正在整理我的桌子:

dynamic discography = new JObject(new JProperty("DiscographyVM", jsonDiscography));
dynamic filmography = new JObject(new JProperty("FilmographyVM", jsonFilmography));

dynamic fullJson = new JArray();
fullJson.Add(discography);
fullJson.Add(filmography);

这会给我一个看起来像这样的 json:

[
  {
    "Discography" : [
      { 
        "Album" : "MyAlbum",
        "Year" : 2017
      },
      { "Album" : "MySecondAlbum",
        "Year" : 2018
      }
    ],
    "Filmography" : [
      {
        "Film" : "MyFirstMovie",
        "Year" : 2017
      },
      {
        "Film" : "MySecondMovie",
        "Year" : 2018
      }
    ]
  }
]

我想要做的是摆脱外部[ ] 括号。所以我想我需要将我的dynamic fullJson 变量更改为其他变量,但我不知道是什么。有什么想法吗?

更新,我正在尝试获取这个结构:

  {
    "Discography" : [
      { 
        "Album" : "MyAlbum",
        "Year" : 2017
      },
      { "Album" : "MySecondAlbum",
        "Year" : 2018
      }
    ],
    "Filmography" : [
      {
        "Film" : "MyFirstMovie",
        "Year" : 2017
      },
      {
        "Film" : "MySecondMovie",
        "Year" : 2018
      }
    ]
  }

【问题讨论】:

  • 您选择 JObject 方式和动态对象是否有特定原因?如果没有:如果你已经在一个普通的 C# 类实例中拥有所有这些信息,你可以在 Web API 中返回它,并且 JSON.NET 将被调用以自动转换它。
  • 我从不同来源收集数据,并用所有电影/专辑填充两个 dynamic jsonDiscography = new JArray();(和 Filmography)。我想将其转换为 json 以在我的客户端中使用,以防万一。由于我现在拥有的外部数组,我只是很难在我的客户端中反序列化它。
  • JSON 约定是将数组序列化为 [ ... ] ,来源:json.org
  • 是的,我知道,我用我正在尝试做的事情更新了这个问题。我正在尝试找到外部数组的替代方法,或者将它们全部放在一起的方法。

标签: c# arrays json serialization mvvm


【解决方案1】:

使用JObject 而不是JArray。让我们看看:

dynamic discography = new JProperty("Discography", jsonDiscography);
dynamic filmography = new JProperty("Filmography", jsonFilmography);

dynamic fulljson = new JObject { discography, filmography };

Try it Online!

注意我也替换

dynamic fullJson = new JObject();
fullJson.Add(discography);
fullJson.Add(filmography);

dynamic fulljson = new JObject { discography, filmography };

【讨论】:

  • 太棒了!我不认为唱片和电影不需要是 JObjects。这正是我想做的最简单的方式。
  • Newtonsoft.Json 是一个很棒的库 :)
  • 哦,看起来更整洁了。再次干杯:)
猜你喜欢
  • 2014-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多