Home > Enterprise >  Add root name to Json string
Add root name to Json string

Time:01-11

I have a code that generate Json string .

public class Work
{
    public string id { get; set; }
    public string name { get; set; }
    public bool status { get; set; }
    public bool open { get; set; }
   
}
public class Root
{
    public IList<Work> work { get; set; }    
}


public void Work_add(string id, string nameM)
    {                    
        _work.Add(new Work()
        {
            id = id,
            name = nameM,
            status = false,
            open = false
        });
    }
    
public List<Work> _work = new List<Work>(); 

public void Print_Json()
{
.
.
string jsonE = JsonConvert.SerializeObject( _work);
}

When a list is populated and then serialised I get this JSON:

[{"id":"1","name":"AAA","status":"false","open":"false"},{"id":"2","name":"BBB","status":"false","open":"false"},{"id":"4","name":"CCC","status":"false","open":"false"},{"id":"5","name":"DDD","status":"false","open":"false"},{"id":"6","name":"EEE","status":"false","open":"false"},{"id":"7","name":"FFF","status":"false","open":"false"},{"id":"8","name":"GGG","status":"false","open":"false"}]

I looked in : https://stackoverflow.com/questions/16294963/json-net-serialize-object-with-root-name and in other solutions, but I'm missing somethings....

I need add "work" name before the list with {}

{"work":[{"id":"1","name":"AAA","status":"false","open":"false"},{"id":"2","name":"BBB","status":"false","open":"false"},{"id":"4","name":"CCC","status":"false","open":"false"},{"id":"5","name":"DDD","status":"false","open":"false"},{"id":"6","name":"EEE","status":"false","open":"false"},{"id":"7","name":"FFF","status":"false","open":"false"},{"id":"8","name":"GGG","status":"false","open":"false"}]}

CodePudding user response:

You should do the following.

public void Print_Json()
{
  var root = new Root();
  root.work = _work;
  string jsonE = JsonConvert.SerializeObject(root);
}
  • Related