简体   繁体   中英

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

I am trying to convert my json into a rule object. I have been following this guide from 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

{
"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. I'm unsure how to assign each field in json to my rules objects. Looking at the newtonsoft docs this should work, but I'm not getting any 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. That property is an array of objects. You need to define and deserialize the root object, eg

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. You can also generate classes by using an online converter like json2csharp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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