Home > Mobile >  how to use ConfigurationBuilder to parse an existing json string (not file)
how to use ConfigurationBuilder to parse an existing json string (not file)

Time:04-05

We know that we can parse json file into IConfigurationRoot as

public class Startup
{
    public IConfigurationRoot Configuration { get; }

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

But I want to use ConfigurationBuilder to parse a json string so can access just like how it works with json file so that I can do:

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

So does imaginal AddJsonString exists or is any third party library I need to use to achieve this?

P.S

I can't use JsonSerializer because the json payload has too many property therefore I can't create a POJO model class to be deserialized with, if there are only 3 or 4 property, then I can certainly do that, but 50 properties (that has nested properties) is a different story

CodePudding user response:

You can use new ConfigurationBuilder().AddJsonStream(new MemoryStream(Encoding.ASCII.GetBytes(jsonString))).Build(); to load json from MemoryStream.

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

  • Related