3

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

2
  • If you just want to read from Json, do you need the configbuilder? Why not just parse the Json string with JsonSerializer? Commented Apr 5, 2022 at 1:27
  • @BenMatthews thanks for your comment, 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 is a different story Commented Apr 5, 2022 at 1:41

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.