C# 如何在asp.net(核心)mvc中读取json
我正在尝试从我的本地文件夹中读取JSON文件,创建对象并将其发送到视图,同时尝试读取JSON文件并动态创建类(即,我希望在基于JSON文件创建类之后,根据我得到的内容,我搜索了很多关于它的信息,有人请帮助) 我的json 我的班级C# 如何在asp.net(核心)mvc中读取json,c#,asp.net-mvc,asp.net-mvc-4,C#,Asp.net Mvc,Asp.net Mvc 4,我正在尝试从我的本地文件夹中读取JSON文件,创建对象并将其发送到视图,同时尝试读取JSON文件并动态创建类(即,我希望在基于JSON文件创建类之后,根据我得到的内容,我搜索了很多关于它的信息,有人请帮助) 我的json 我的班级 public class Environmet { public string Name { get; set; } Env_properties prop { get; set; } } public class
public class Environmet
{
public string Name { get; set; }
Env_properties prop { get; set; }
}
public class Env_properties
{
public string resourcegroup { get; set; }
public string storageaccount { get; set; }
public string azuresqlserver { get; set; }
public string container{ get; set; }
public string sourcesqlserver { get; set; }
}
我的控制器
public IActionResult Env()
{
var json = System.Path("wwwroot/data/sample.json");
var json = System.IO.ReadAllText(Server.MapPath("wwwroot/data/sample.json"));
return View();
}
根据您当前的JSON,这些类必须如下所示:
public class Dev
{
public string resourcegroup { get; set; }
public string storageaccount { get; set; }
public string azuresqlserver { get; set; }
public string container { get; set; }
public string sourcesqlserver { get; set; }
}
public class Qa
{
public string resourcegroup { get; set; }
public string storageaccount { get; set; }
public string azuresqlserver { get; set; }
public string container { get; set; }
public string sourcesqlserver { get; set; }
}
public class Example
{
public Dev Dev { get; set; }
public Qa qa { get; set; }
}
var obj = JsonSerializer.Deserialize<Example>(json );
我是根据你的JSON生成的
将输入JSON与生成的类反序列化如下:
public class Dev
{
public string resourcegroup { get; set; }
public string storageaccount { get; set; }
public string azuresqlserver { get; set; }
public string container { get; set; }
public string sourcesqlserver { get; set; }
}
public class Qa
{
public string resourcegroup { get; set; }
public string storageaccount { get; set; }
public string azuresqlserver { get; set; }
public string container { get; set; }
public string sourcesqlserver { get; set; }
}
public class Example
{
public Dev Dev { get; set; }
public Qa qa { get; set; }
}
var obj = JsonSerializer.Deserialize<Example>(json );
var obj=JsonSerializer.Deserialize(json);
这是否回答了您的问题?以及hii,您可以帮助如何使用NJsonSchema.CodeGeneration从子模式包装c#类。我指的是如何从文件中读取json shema并创建类。我看了很多文件不懂的东西。请添加一些代码剪贴集。非常感谢。