如何在C#中反序列化指定JSON字符串并获取MaxTargets值?
解决JSON反序列化获取MaxTargets值的问题
核心问题梳理
你当前的代码和模型存在两处关键错误:
ConfigProperties在JSON中是对象结构,但模型里定义为string类型,无法完成正确反序列化- 整个JSON是包含
runtimeOptions的单个对象,而非List<OptionalInclude>集合,强行转列表会导致失败
修正后的模型定义
调整模型层级,完全匹配JSON结构:
// 对应整个JSON的根模型 public class RootConfig { [JsonProperty("runtimeOptions")] public RuntimeOptions RuntimeOptions { get; set; } } // 对应JSON中的runtimeOptions节点(原OptionalInclude命名更贴合语义的调整) public class RuntimeOptions { [JsonProperty("tfm")] public string Tfm { get; set; } [JsonProperty("frameworks")] public IList<Dictionary<string, string>> Frameworks { get; set; } // 修正为字典类型,匹配JSON里的对象结构 [JsonProperty("configProperties")] public Dictionary<string, string> ConfigProperties { get; set; } }
正确的反序列化代码
直接反序列化为根模型,即可快速获取MaxTargets值:
var optionalIncludesConfig = File.ReadAllText(configPath); var rootConfig = JsonConvert.DeserializeObject<RootConfig>(optionalIncludesConfig); // 获取MaxTargets的值 string maxTargets = rootConfig.RuntimeOptions.ConfigProperties["MaxTargets"];
可选优化:强类型替代字典
如果希望类型更严谨,可以给configProperties单独定义类:
public class ConfigProperties { [JsonProperty("MaxTargets")] public string MaxTargets { get; set; } } // 修改RuntimeOptions中的对应属性 [JsonProperty("configProperties")] public ConfigProperties ConfigProperties { get; set; } // 获取值的方式变为 string maxTargets = rootConfig.RuntimeOptions.ConfigProperties.MaxTargets;
内容的提问来源于stack exchange,提问作者Krishna Rangampally
相关产品推荐
相关产品推荐

