我们知道,我们可以将json文件解析为IConfigurationRoot

public class Startup
{
    public IConfigurationRoot Configuration { get; }

    public Startup(IHostingEnvironment env)
    {
        this.Configuration = new ConfigurationBuilder()
            .SetBasePath(path)
            .AddJsonFile("somefile.json")
            .Build();
    }   
}

但我想用ConfigurationBuilder来解析json字符串,这样就可以像访问json文件一样进行访问,这样我就可以:

string jsonString = XXX(); // external calls to get json
var config = new ConfigurationBuilder().AddJsonString(jsonString).Build();
string name = config["Student:Name"];

那么imaginal AddJsonString是否存在,或者我是否需要使用任何第三方库来实现这一点?

附笔

我不能使用JsonSerializer,因为json负载有太多的属性,因此我无法创建要反序列化的POJO模型类,如果只有3或4个属性,那么我当然可以这样做,但50个属性(具有嵌套属性)是另一回事

推荐答案

可以使用new ConfigurationBuilder().AddJsonStream(new MemoryStream(Encoding.ASCII.GetBytes(jsonString))).Build();从MemoryStream加载json.

My test Code:

public Startup(IConfiguration configuration, IWebHostEnvironment env)
{
    Configuration = configuration;

    string jsonString = "{\"source\": \"test.com\", \"Time\":\"Feb 2019\" }"; // external calls to get json

    var config = new ConfigurationBuilder().AddJsonStream(new MemoryStream(Encoding.ASCII.GetBytes(jsonString))).Build();

    string name = config["source"];
}

Test Result(.Net Core 3.1):

enter image description here

Json相关问答推荐

PowerShell:将Invoke-WebRequest与变量一起使用

属性错误:';ActivitiesClient';对象没有属性';base_url';

基于 JSON 字段的 Jolt 条件标志

震动范围改善

XSLT 3.0 Json-to-xml,json 包含 html struct

(已回答)JSON 读取函数返回未定义而不是预期值 - Typescript

如何在 JSonPath 中按值查找列表中的所有元素

使用 REACT 从字段值中读取 JSON 元素

从 json 数组中仅提取一个值导致 vb6

PowerShell - JSON/PsCustomObject - 为什么我的数组被扁平化为一个对象?

JBuilder中未定义的局部变量或方法json

Android JSON 库的性能和可用性比较

如何在已声明的 JSON 对象中添加键值对

ASP.NET MVC 读取原始 JSON 发布数据

将循环 struct 转换为 JSON - 有什么方法可以找到它抱怨的字段?

从 Json 对象 Android 中获取字符串值

带有 Jackson 的不可变 Lombok 注释类

处理 HTTP 请求正文中的可选 JSON 字段

在 iPhone 上解析 JSON 日期

在 C# 中反序列化 JSON 数组