Create nested json with c#

前端 未结 4 1993
日久生厌
日久生厌 2021-02-09 14:56

I am able to create a flat serialized JSON string pretty easily with c#

My issue is I want to create a nested string like this below

[ { 
    title: \"Y         


        
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-09 15:25

    You can make use of the ExpandoObject under the System.Dynamic namespace.

    Here is a small snippet for achieving your solution:

    dynamic parameters = new dynamic[2];
    
    parameters[0] = new ExpandoObject();
    parameters[0].title = "Yes";
    parameters[0].id = "1";
    
    parameters[0].menu = new dynamic[1];
    parameters[0].menu[0] = new ExpandoObject();
    
    parameters[0].menu[0].title = "Maybe";
    parameters[0].menu[0].id = "3";
    parameters[0].menu[0].alert = "No";
    parameters[0].menu[0].menu = new dynamic[1];
    parameters[0].menu[0].menu[0] = new ExpandoObject();
    parameters[0].menu[0].menu[0].title = "Maybe Not";
    parameters[0].menu[0].menu[0].id = "8";
    parameters[0].menu[0].menu[0].alert = "No";
    parameters[0].menu[0].menu[0].menu = new dynamic[0];
    
    parameters[1] = new ExpandoObject();
    parameters[1].title = "No";
    parameters[1].id = "2";
    parameters[1].menu = new dynamic[0];
    
    
    string json = JsonConvert.SerializeObject(parameters, Formatting.Indented);
    Console.WriteLine(json);
    

    Here is the work in fiddle

    Note: There are other ways to achieve this, but I have been using this approach.

提交回复
热议问题