简体   繁体   English

使用 ZEE9B16F39BC3629FB97E10A12A7B004 将 JSON 反序列化为 c# 中的 object

[英]Deserializes JSON to an object in c# using json.net

I am trying to convert my json into a rule object.我正在尝试将我的 json 转换为规则 object。 I have been following this guide from Newtonsoft http://www.newtonsoft.com/json/help/html/deserializeobject.htm .我一直在关注 Newtonsoft http://www.newtonsoft.com/json/help/html/deserializeobject.htm的本指南。

public class Rule{
            public string Field { get; set; }
            public string Test { get; set; } 
            public Rule[] Cases { get; set; }
            } 
 public class Rules    {
        public List<Rule> Root{ get; set; } 
    }

My Json from rules.js我的 Json 来自 rules.js

{
"Rules": [{
        "Field": "Subject",
        "Test": "^(Azure Exception)",
        "Cases": [{
            "Field": "Content",
            "Test": "Hostname: az.....(?<Hostname>[^\n])",
            "Cases": [{
                "Field": "Content",
                "Test": "Hostname:\\s+(?<Hostname>.*)\\s+Site name:\\s+(?<SiteName>.*)"
            }]
        }]
    }]
}

In my main method:在我的主要方法中:

String RulesFile = "cSharp/rules.js"; 
String Json = System.IO.File.ReadAllText(RulesFile); 

Rule rule = JsonConvert.DeserializeObject<Rule>(Json);

var rules = JsonConvert.DeserializeObject<Rules>(Json);
        //rule.Cases
        //rule.Field
        //rule.Test
        //rules.Root
     
Console.Write(rule.Field);
 

I've tested my json and i can output it in my terminal.我已经测试了我的 json 并且我可以在我的终端中使用 output 它。 I'm unsure how to assign each field in json to my rules objects.我不确定如何将 json 中的每个字段分配给我的规则对象。 Looking at the newtonsoft docs this should work, but I'm not getting any output.查看 newtonsoft 文档,这应该可以,但我没有得到任何 output。

I want to be able to print these fields out, anyone know to do it?我希望能够将这些字段打印出来,有人知道吗?

Cheers all in advance.提前祝大家好运。

In your JSON string, the root object is an object with a Rules property.在您的 JSON 字符串中,根 object 是具有Rules属性的 object。 That property is an array of objects.该属性是一个对象数组。 You need to define and deserialize the root object, eg您需要定义和反序列化根 object,例如

class Rules 
{
    public Rule[] Rules{get;set;}
}

var rules = JsonConvert.DeserializeObject<Rules>(Json);

You can generate the DTOs requires for deserialization in Visual Studio by copying the JSON string and select Paste JSON as Classes in the Edit menu.您可以通过在编辑菜单中复制 JSON 字符串和 select 将 JSON 粘贴为类来生成 Visual Studio 中反序列化所需的 DTO。 You can also generate classes by using an online converter like json2csharp您还可以使用json2csharp等在线转换器生成类

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM