Kim
Kim

Reputation: 437

Create tree hierarchy in json.net with LINQ using c#

I looked at this Create tree hierarchy in JSON with LINQ question and answer and it's close to what I need. However I can't generate the nested array as shown below as I am using json.net

Class.cs

    public class RootObject
    {
        public List<Attribute> test { get; set; }
    }
    public class Attribute
    {
        public string testKey { get; set; }
        public string start { get; set; }
        public string finish { get; set; }
        public string comment { get; set; }
        public string status { get; set; }
    }


    public class AttributeData
    {
        public Attribute AttributeDataOps()
        {
            ***Attribute DATA***
        }
    }

Program.cs

Attribute attribute = new Attribute();
AttributeData attributeData = new AttributeData();
string JSONresult = JsonConvert.SerializeObject(attribute);
string path = @"C:\file.json";

Expected Result

{
    "tests" : [
        {
            "testKey" : "",
            "start" : "",
            "finish" : "",
            "comment" : "",
            "status" : ""
        }
    ]
}

Current Result

    {
        "testKey" : "",
        "start" : "",
        "finish" : "",
        "comment" : "",
        "status" : ""
    }

Upvotes: 4

Views: 204

Answers (1)

Eldho
Eldho

Reputation: 8301

Your expecting a collection but your passing a single object to serialize.

var rootObject = new RootObject();
List<Attribute> attribute = new List<Attribute>();
rootObject.test = attribute;
string JSONresult = JsonConvert.SerializeObject(rootObject);

Upvotes: 4

Related Questions