转换JSON ToList并将其解析为EF模型



我正在尝试在读取C#中ToList的json文件后将其转换,然后将其传递给我的模型并将其添加到数据库中。现在,我的问题是:我该怎么做?

这是我的儿子:

{
"Course: 1": {
"Name": "Fundamentals of Yoga",
"Category": "Health & Fitness",
"Headline": "An all levels guide to your yoga practice.",
"CreatedBy": "Carleen Rose",
"ExternalImage": "https://udemy-images.udemy.com/course/750x422/1854410_de8b.jpg",
"Duration": "5 hours",
"Description": {
"What You'll Learn": [
"You'll have a great understanding of the foundations of yoga and basic anatomy so you'll safely be able to practice yoga anywhere!",
"You'll be comfortable practicing in a public class and confident enough to practice yoga at home."
],
"Requirements": [
"The desire to begin or deepen your yoga practice!",
"A place to practice, preferably on a yoga mat."
],
"Description": "<div>n                    Descriptionn                </div>nn                <p>Imagine building a house with the roof first. Or growing a tree starting with it's branches. Crazy right?&nbsp; Yet that's how many people start their yoga practice, with the imagined "finished product" they're trying to achieve. Even for a practiced yogi this can result in not knowing what you're doing or getting hurt.&nbsp; So many classes are still taught u201cpose firstu201d but this revolutionary class is designed foundation first.</p><p>This course will start your practice from it's foundation or roots. It uses anatomy and physics to build your poses in a healthy alignment for your body and optimize your practice. It also activates your deep core strength, heats up your body and transitions you through poses in a way that gets you more results in less time and makes transformation accessible on all levels.</p><p>Whether you're looking for beginner yoga or something more advanced, this course will help you take your yoga practice to the next level.</p><p>Ready to channel your inner-superhero and transform your yoga practice? Then I'll see you on the mat! Namaste!!</p><p><strong>This course includes:</strong></p><ul><li><p>Workshop style videos teaching the foundations of yoga asana and anatomy</p></li><li><p>Topics and philosophies not normally discussed in a yoga class</p></li><li><p>Variety of complete yoga flows for your home practice</p></li><li><p>Pose tutorials of fun and challenging yoga poses</p></li><li><p>Surprise bonus material!</p></li></ul>nn                n                    <div class="audience" data-purpose="course-audience">n                        <div class="audience__title">n                            Who is the target audience?n                        </div>n                        <ul class="n                            n                                <li>Anyone who wants to build a lifelong yoga practice and enjoy all the benefits of yoga.</li>n                            n                                <li>Any level yogi, especially if you're wanting to take your practice outside of the yoga studio.</li>n                            n                                <li>Beginner yogis who want to learn the basics of yoga and start out their yoga journey.</li>n                            n                                <li>Advanced yogis who want to expand their practice and take it to the next level.</li>n                            n                        </ul>"
}
},
"Course: 2": {
"Name": "Complete Forex Trading- At Price Action Tricks and Tips",
"Category": "Business",
"Headline": "Recognise Market Trend And Start Interday or long term trading without taking big risk and get huge profit",
"CreatedBy": "Rizwan azim",
"ExternalImage": "https://udemy-images.udemy.com/course/750x422/2023746_5bba_2.jpg",
"Duration": "1 hour",
"Description": {
"What You'll Learn": [
"Become professional trader and can earn good profit in forex buisness"
],
"Requirements": [
"Just Have Pc and Internet Connection"
],
"Description": "<div>n                    Descriptionn                </div>nn                <p>ake this course now and learn from my Long Time experience.</p><p> Avoid the most common pitfalls that catch 90% of traders!</p><p>Everything I explain here at live Mt4 Chart step by step </p><p>by live examples</p><p>Recognise Market Trend And Start Interday or long term trading</p><p>without taking big risk and get huge profit from every Trade </p><p><br></p><p> All you need is an open mind and a passion to be successful!</p><p><br></p><p>you have unlimited lifetime access at no extra costs, </p><p>ever</p><p>all future additional lectures, bonuses, etc</p><p><br></p>nn                n                    <div class="audience" data-purpose="course-audience">n                        <div class="audience__title">n                            Who is the target audience?n                        </div>n                        <ul class="n                            n                                <li>Every business mind person who want to earn big profit in Short time</li>n                            n                        </ul>"
}
}
}

我的后模型类:

[Table("Post")]
public partial class Post
{
[Key]
public int Id { get; set; }
[Required]
[Display(Name = "Title")]
[StringLength(150)]
public string Name { get; set; }
[AllowHtml]
[Display(Name = "Description")]
[Column(TypeName = "text")]
public string Description { get; set; }
[Display(Name = "External Image")]
[Required]
[StringLength(200)]
public string ExternalImage { get; set; }
[Display(Name = "Author")]
[StringLength(150)]
public string CreatedBy { get; set; }    
[Display(Name = "Size")]
[StringLength(150)]
public string Size { get; set; }
[Display(Name = "Category")]
public int? Category_id { get; set; }
[Display(Name = "Date")]
public DateTime PublishDate { get; set; }
[Display(Name = "Duration")]
[StringLength(150)]
public string Duration { get; set; }

}

这是我的代码:

using (StreamReader r = new StreamReader("/data.json"))
{
string json = r.ReadToEnd();
dynamic array = JsonConvert.DeserializeObject(json);
foreach (var item in array)
{
var ii = item;
}
}

我需要做的只是:

  1. 转换Json数据=>Tolist((
  2. 从foreach循环读取
  3. 将"值"指定给模型并将其保存到数据库中

我建议首先创建一些类来建模JSON:

public class Course
{
public string Name { get; set; }
public string Category { get; set; }
public string Headline { get; set; }
public string CreatedBy { get; set; }
public string ExternalImage { get; set; }
public string Duration { get; set; }
public Description Description { get; set; }
}
public class Description
{
[JsonProperty("What You'll Learn")]
public List<string> WhatYoullLearn { get; set; }
public List<string> Requirements { get; set; }
[JsonProperty("Description")]
public string DescriptionHtml { get; set; }
}

然后,我建议取消分类,如下所示:

var json = File.ReadAllText("/data.json");
var courses = JsonConvert.DeserializeObject<Dictionary<string, Course>>(json);
foreach (var course in courses)
{
var courseName = course.Key;
var courseDetails = course.Value;
// Do something with the data, e.g save it to your database
}

最新更新