Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
89 views
in Technique[技术] by (71.8m points)

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>[^
])",
            "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.

question from:https://stackoverflow.com/questions/65626493/deserializes-json-to-an-object-in-c-sharp-using-json-net

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...