让我们假设我们在appsettings.json中有这个部分
{
"crypto":{
"A": "some value",
"B": "foo foo",
"C": "last part"
},
...
}其中"crypto"是某个密钥的json序列化。
在后面的代码中,我需要这样做:
var keyOptions = CryptoProvider.RestoreFromJson(Configuration.GetSection("crypto"))但是Configuration.GetSection返回ConfigurationSection实例。有没有办法以某种方式获得原始的json数据?
我认为ConfigurationSection.Value应该能做到这一点,但由于某些原因,它总是null。
发布于 2020-07-20 22:44:41
这是一个实施的例子。
private static JToken BuildJson(IConfiguration configuration)
{
if (configuration is IConfigurationSection configurationSection)
{
if (configurationSection.Value != null)
{
return JValue.CreateString(configurationSection.Value);
}
}
var children = configuration.GetChildren().ToList();
if (!children.Any())
{
return JValue.CreateNull();
}
if (children[0].Key == "0")
{
var result = new JArray();
foreach (var child in children)
{
result.Add(BuildJson(child));
}
return result;
}
else
{
var result = new JObject();
foreach (var child in children)
{
result.Add(new JProperty(child.Key, BuildJson(child)));
}
return result;
}
}发布于 2016-05-31 03:02:02
如果您想要获取crypto部分的内容,可以使用Configuration.GetSection("crypto").AsEnumerable()(或者对于您的示例,Configuration.GetSection("crypto").GetChildren()可能很有用)。
但是结果不是原始的json。您需要对其进行转换。
发布于 2019-11-12 21:10:02
我可能没有弄清楚问题和上下文,但是如果您想使用原始的json或json令牌,您可能应该使用Newtonsoft library。
例如,承认配置是一个对象,您可以使用JsonConvert.SerializeObject()来将您的对象转换为JSON字符串(反过来也是如此)。您还可以使用同一个包中提供的包含JObject工具的LINQ库。
例如,下面的代码只是读取包含给定序列化对象的json文件,并加载到一个.Net对象中。
String filecontent = "";
StreamReader s = new StreamReader(file.OpenReadStream());
filecontent = s.ReadToEnd();
contractList = JsonConvert.DeserializeObject<YourObject>(filecontent); 我真的不知道我是否做对了,但是这个问题把我搞糊涂了。举个例子,你能精确的告诉我你是如何加载你的json的吗?你存储它的对象是哪种类型(我猜是配置类型?)?等等……
https://stackoverflow.com/questions/37525604
复制相似问题