.NetCore gets the configuration content of the json file

The data configuration and content in .netcore replace the xml file of the previous framework with json file, so how to obtain the data in json? The following explains how to obtain json file in .net core.

(1): First, create a new .net core web application, then create a new folder JsonFile, and create a new class.json file in the JsonFile folder.


(2): Right-click class.json and set the assignment to the output directory to: always copy (very important).


(3): Then add content to class.json:

{
  "ClassNum": "1",
  "ClassName": "Grade 1 and 1",
  "Students": [
    {
      "name": "Obama",
      "age": 50
    },
    {
      "name": "普京",
      "age": 55
    }
  ]
}

(4): Right-click the project dependencies: manage the GuGet package, add the Microsoft.Extensions.Configuration assembly to the project


(5): Finally, add the relevant code to obtain the json file data in the Home controller

namespace CoreDemo.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            var builder = new ConfigurationBuilder().AddJsonFile("JsonFile/class.json");
            var config = builder.Build();
            string str = "Class is: "+ config["ClassNum"]+"/";
            return Content("Class number="+config["ClassNum"]+", class name="+ config["ClassName"]+"\r"
                +"Student name="+config["Students:0:name"]+",Student age="+ config["Students:0:age"]
            );
        }
    }
}

(6): Run the project, display the running result, the data has been read and displayed in the browser, indicating that the function of obtaining the configuration content of the json file has been realized.


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324595470&siteId=291194637