【问题标题】:How to parse complex json to c# .net classes [closed]如何将复杂的 json 解析为 c# .net 类 [关闭]
【发布时间】:2021-04-26 14:15:25
【问题描述】:

我的 json 如下所示。我需要将其转换为 c# 类。请注意,所有值在实际情况下会有所不同。

{
  'aa-AA': {
    lanCODE: 'aa-AA',
    genNames: {
      female: ['Wavenet'],
      male: ['Bavenet', 'Bavenet'],
    },
    default: 'Wavenet',
    systemLocale: ['ara', 'aru', 'are', 'aro', 'arh', 'arm', 'arq', 'ark'],
    name: 'xxxx',
  },
  'aa-AA': {
    lanCODE: 'aa-AA',
    genNames: {
      female: ['Wavenet'],
      male: ['Bavenet', 'Bavenet'],
    },
    default: 'Wavenet',
    systemLocale: ['ara', 'aru', 'are', 'aro', 'arh', 'arm', 'arq', 'ark'],
    name: 'xxxx',
  },
  'aa-AA': {
    lanCODE: 'aa-AA',
    genNames: {
      female: ['Wavenet'],
      male: ['Bavenet', 'Bavenet'],
    },
    default: 'Wavenet',
    systemLocale: ['ara', 'aru', 'are', 'aro', 'arh', 'arm', 'arq', 'ark'],
    name: 'xxxx',
  }
 }

【问题讨论】:

  • JSON 的复杂性是否来自它的格式错误且无效?
  • 你试过了吗?
  • “您需要”与您尝试过的不同。请发布您在 c# 中尝试过的内容以及它所面临的挑战,以便我们帮助您解决问题。
  • 格式错误是:使用单引号'而不是双引号,属性名称必须双引号"。尾随逗号是非法的([1,2,3 , ]=> 非法)

标签: c# json json.net


【解决方案1】:

初始属性几乎可以肯定是字典键,所以我会使用这样的东西:

public class Language
{
    [JsonProperty("lanCODE")]
    public string LanguageCode { get; set; }
    
    public string Default { get; set; }

    public List<string> SystemLocale { get; set; }

    public GenNames GenNames { get; set; }
}

public class GenNames
{
    public List<string> Female { get; set; }
    public List<string> Male { get; set; }
}

然后像这样反序列化:

var languages = JsonConvert.DeserializeObject<Dictionary<string, Language>>(json);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-20
    • 1970-01-01
    • 2017-12-05
    • 2020-03-18
    相关资源
    最近更新 更多