C# JSON.NET反序列化程序返回Null
编辑:它与try/catch return null语句无关。我对它进行了调试和观看,并确保它不会进入捕捉区。我甚至把它注释掉了,没有用 我为我的应用程序构建一个配置管理器已经很累了。本质上,我有一些变量需要存储在JSON文件中,并在应用程序启动期间读取,以便知道某些值 对于其中一些配置变量,我将允许用户覆盖默认值,因此如果用户密钥具有非空字符串,我将使用该字符串。如果没有用户密钥或存在空字符串,我将使用默认值。为了满足这个需求,我编写了AllowUserConfig和CoalesceUserDefault方法来处理这个问题 此时,我在下面有一个JSON文件。我复制了数据并作为一个类JSONConfig粘贴到VisualStudio中。然后,我有一个执行实际工作的ConfigManager文件,我的program.cs调用ConfigManager以使用反序列化ConfigVariables方法读取位于正确位置的配置文件,并从中创建JSONConfig对象 话虽如此,DeserializeConfigVariables中的JSONConfig对象在configVariables=serializer.DeserializejsonReader;行上返回为null;。有什么我不知道的吗。每件事我都检查了一百遍,看不出我做错了什么 任何和所有的帮助都将不胜感激 这是我的JSON:C# JSON.NET反序列化程序返回Null,c#,json.net,C#,Json.net,编辑:它与try/catch return null语句无关。我对它进行了调试和观看,并确保它不会进入捕捉区。我甚至把它注释掉了,没有用 我为我的应用程序构建一个配置管理器已经很累了。本质上,我有一些变量需要存储在JSON文件中,并在应用程序启动期间读取,以便知道某些值 对于其中一些配置变量,我将允许用户覆盖默认值,因此如果用户密钥具有非空字符串,我将使用该字符串。如果没有用户密钥或存在空字符串,我将使用默认值。为了满足这个需求,我编写了AllowUserConfig和CoalesceUserD
{
"format": {
"date": {
"default": "yyyyMMdd",
"user": ""
},
"month_year": {
"default": "MM_YYYY",
"user": ""
}
},
"placeholders": {
"current_date": "{date}",
"month_year": "{month_year}",
"last_monday": "{prev_monday}",
"next_monday": "{next_monday}"
},
"resource_locations": {
"directories": {
"root_working": {
"default": "C:\\ALL",
"user": ""
},
"exports": {
"default": "C:\\ALL\\Exports",
"user": ""
},
"completed_exports": {
"default": "C:\\ALL\\Done",
"user": ""
},
"archived": {
"default": "C:\\ALL\\Archives",
"user": ""
}
},
"compression": {
"filename": {
"default": "{next_monday}_daily_{date}.zip",
"user": ""
}
},
"logging": {
"directory": "logs",
"process_filename": "activity_log_{month_year}.log",
"process_error_filename": "errors.log",
"system_error_filename": "sys_errors.log"
}
}
}
这是通过在Visual Studio中将JSON复制和粘贴为类而创建的JSONConfig类I:
using System;
using Newtonsoft.Json;
namespace Config
{
public class JSONConfig
{
public RootObject ConfigVariables { get; set; }
}
public class RootObject
{
public Format format { get; set; }
public Placeholders placeholders { get; set; }
public Resource_Locations resource_locations { get; set; }
}
public class Format
{
public Date date { get; set; }
public Month_Year month_year { get; set; }
}
public class Date
{
public string _default { get; set; }
public string user { get; set; }
}
public class Month_Year
{
public string _default { get; set; }
public string user { get; set; }
}
public class Placeholders
{
public string current_date { get; set; }
public string month_year { get; set; }
public string last_monday { get; set; }
public string next_monday { get; set; }
}
public class Resource_Locations
{
public Directories directories { get; set; }
public Compression compression { get; set; }
public Logging logging { get; set; }
}
public class Directories
{
public Root_Working root_working { get; set; }
public Exports exports { get; set; }
public Completed_Exports completed_exports { get; set; }
public Archived archived { get; set; }
}
public class Root_Working
{
public string _default { get; set; }
public string user { get; set; }
}
public class Exports
{
public string _default { get; set; }
public string user { get; set; }
}
public class Completed_Exports
{
public string _default { get; set; }
public string user { get; set; }
}
public class Archived
{
public string _default { get; set; }
public string user { get; set; }
}
public class Compression
{
public Filename filename { get; set; }
}
public class Filename
{
public string _default { get; set; }
public string user { get; set; }
}
public class Logging
{
public string directory { get; set; }
public string process_filename { get; set; }
public string process_error_filename { get; set; }
public string system_error_filename { get; set; }
}
}
然后,在我的ConfigManager文件中,我有以下内容:
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace Config
{
static class ConfigManager
{
// Assumes parent directory is bin. Assumes config is sibling to bin.
private static string _initialConfig = @"config\config.json";
public static string ConfigPath() => Path.Combine(GetRootAppDir(), _initialConfig);
public static string Parent(string directory)
{
string parentDirectory = Directory.GetParent(directory).FullName;
return parentDirectory;
}
public static string GetRootAppDir()
{
return Parent(Parent(Directory.GetCurrentDirectory()));
}
public static JSONConfig DeserializeConfigVariables()
{
try
{
var configVariables = new JSONConfig();
var serializer = new JsonSerializer();
Console.WriteLine($"Config Path: {ConfigPath()}"); //testing
using (var reader = new StreamReader(ConfigPath()))
using (var jsonReader = new JsonTextReader(reader))
{
configVariables = serializer.Deserialize<JSONConfig>(jsonReader);
}
return configVariables;
}
catch (System.IO.DirectoryNotFoundException ex)
{
Console.WriteLine(ex.Message);
return null;
}
}
public static bool AllowUserConfig(object configVariable)
{
string userFieldName = "user";
var objType = configVariable.GetType();
return objType.GetMethod(userFieldName) != null;
}
public static string CoalesceUserDefault(dynamic configVariable)
{
if (AllowUserConfig(configVariable))
{
if (!(String.IsNullOrEmpty(configVariable.user)))
{
return configVariable.user;
}
}
return configVariable._default;
}
}
}
希望对你有帮助
您可以添加您的jsonfile.json文件
e、 g.:-
yourjsonfile.json
另一个jsonfile.json
确保yourjsonfile.json和另一个jsonfile.json文件属性将Copy To Output Directory设置为始终复制
从yourjsonfile.json和其他类似的jsonfile.json文件中查找值-
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
IConfiguration configuration = builder.Build();
string GetValue1 = configuration.GetSection("key1").Value;
string GetValue2 = configuration.GetSection("key2").Value;
var builder1 = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(configuration.GetConnectionString("$ref").Replace("#", ""), optional: true, reloadOnChange: true);
IConfiguration configuration1 = builder1.Build();
GetValue2 = (configuration1.GetSection("key2").Value) != null ? configuration1.GetSection("key2").Value : GetValue2;
谢谢 您的Json在根目录中不包含名为ConfigVariable的属性,该属性是在类JSONConfig中定义的,您正试图反序列化的类型 如果您检查Json,它适合RootObject的定义。您应该将类反序列化为RootObject的实例。如果您想将配置存储在JsonConfig的实例中,可以将其分配给JsonConfig实例的ConfigVariable属性
configVariables.ConfigVariables = serializer.Deserialize<RootObject>(jsonReader);
您需要将json反序列化为RootObject,而不是JSONConfig 推荐 将反序列化JSON的方法也更改为更简单的过程
public static RootObject DeserializeConfigVariables()
{
return JsonConvert.DeserializeObject<RootObject>(File.ReadAllLines(ConfigPath()));
}
Json文件与用于反序列化它的对象结构不对应。 JsonConfig文件包含ConfigVariables属性,但json文件包含格式、占位符、资源位置属性,这些属性应位于第二级。 尝试按以下方式更新配置文件:
{
"ConfigVariables": {
"format": {
"date": {
"default": "yyyyMMdd",
"user": ""
},
"month_year": {
"default": "MM_YYYY",
"user": ""
}
},
"placeholders": {
"current_date": "{date}",
"month_year": "{month_year}",
"last_monday": "{prev_monday}",
"next_monday": "{next_monday}"
},
"resource_locations": {
"directories": {
"root_working": {
"default": "C:\\ALL",
"user": ""
},
"exports": {
"default": "C:\\ALL\\Exports",
"user": ""
},
"completed_exports": {
"default": "C:\\ALL\\Done",
"user": ""
},
"archived": {
"default": "C:\\ALL\\Archives",
"user": ""
}
},
"compression": {
"filename": {
"default": "{next_monday}_daily_{date}.zip",
"user": ""
}
},
"logging": {
"directory": "logs",
"process_filename": "activity_log_{month_year}.log",
"process_error_filename": "errors.log",
"system_error_filename": "sys_errors.log"
}
}
}
}
它会解决你的问题。
顺便说一句,正如我看到的,您在配置对象中以json样式命名了属性。例如,资源位置最好以常规方式命名属性,并添加JsonProperty属性以正确映射。
e、 g
非常感谢你!我明白我现在做错了什么。谢谢,谢谢。我还不太明白这一点,但我会看看我是否可以找到如何使用它,如果它将更有效地为我的应用程序。谢谢。@Yijafe如果您想在应用程序中全局使用这些JSON值,请使用我的代码,否则请使用此代码-serializer.DeserializejsonValue;非常感谢。我没有编辑json文件,而是引用了rootobject。非常感谢。另外,关于类名,这是VisualStudio默认创建它们的方式。我将看看是否有一种方法,使他们帕斯卡案件自动。我刚贴了一个小样本。我删除了更多的类和JSON对象,因此手动更新它们需要一些时间。谢谢,这就解决了。非常感谢你的帮助!
configVariables = serializer.Deserialize<RootObject>(jsonReader);
{ "ConfigVariables" :
{
"format": {
"date": {
"default": "yyyyMMdd",
"user": ""
...
public static RootObject DeserializeConfigVariables()
{
return JsonConvert.DeserializeObject<RootObject>(File.ReadAllLines(ConfigPath()));
}
{
"ConfigVariables": {
"format": {
"date": {
"default": "yyyyMMdd",
"user": ""
},
"month_year": {
"default": "MM_YYYY",
"user": ""
}
},
"placeholders": {
"current_date": "{date}",
"month_year": "{month_year}",
"last_monday": "{prev_monday}",
"next_monday": "{next_monday}"
},
"resource_locations": {
"directories": {
"root_working": {
"default": "C:\\ALL",
"user": ""
},
"exports": {
"default": "C:\\ALL\\Exports",
"user": ""
},
"completed_exports": {
"default": "C:\\ALL\\Done",
"user": ""
},
"archived": {
"default": "C:\\ALL\\Archives",
"user": ""
}
},
"compression": {
"filename": {
"default": "{next_monday}_daily_{date}.zip",
"user": ""
}
},
"logging": {
"directory": "logs",
"process_filename": "activity_log_{month_year}.log",
"process_error_filename": "errors.log",
"system_error_filename": "sys_errors.log"
}
}
}
}
[JsonProperty('resource_locations')]
public ResourceLocations ResouceLocations { get; set; }