使用 Json.net 将 json 对象反序列化为 SQL 数据库

本文关键字:反序列化 SQL 数据库 对象 json Json net 使用 | 更新日期: 2023-09-27 18:18:16

我想使用 Json.net 将 json 对象反序列化为 SQL DB

Json 文件:

{
  "requirements": {
    "requirement": [
      {
        "Id": "req1",
        "desc": "description of requirement1"
      },
      {
        "Id": "req2",
        "desc": "description of requirement2",
      },
      {
        "desc": "description of requirement3",
        "Id": "req3"
      }
    ]
  }
}
这样,"Id"属性的值应放在需求表的 ID 列中

,"desc"属性的值应放在要求表的 DESC 列中

    ID        DESC
    req1      description of requirement1                       
    req2      description of requirement2                       
    req3      description of requirement3       

使用 Json.net 将 json 对象反序列化为 SQL 数据库

您可以使用 json2sharp 工具生成类,并使用像这样反序列化对象。

    public class Requirement
    {
        public string Id { get; set; }
        public string desc { get; set; }
    }
    public class Requirements
    {
        public List<Requirement> requirement { get; set; }
    }
    public class RootObject
    {
        public Requirements requirements { get; set; }
    }

 var x =JsonConvert.DeserializeObject<RootObject>(json);

并使用OrderByDescending

x.requirements.requirement.OrderByDescending(d => d.Id);
        string json = "{'"requirements'": {'"requirement'": [{'"Id'": '"req1'",'"desc'": '"description of requirement1'"},{'"Id'": '"req2'",'"desc'":'"description of requirement2'",},{'"desc'": '"description of requirement3'",'"Id'": '"req3'"}]}}";
        //Deserialize using Json.Net
        var objectRequirement = JsonConvert.DeserializeObject<RootObject>(json);
        //Add it to your database
        foreach (var item in objectRequirement.requirements.requirement)
        {
            db.Requirement.Add(new Requirement { ID = item.Id, DESC = item.desc });
        }
        db.SaveChanges();

<小时 />您可以使用 http://json2csharp.com/来创建类:

    public class Requirement
    {
        public string Id { get; set; }
        public string desc { get; set; }
    }
    public class Requirements
    {
        public List<Requirement> requirement { get; set; }
    }
    public class RootObject
    {
        public Requirements requirements { get; set; }
    }