2016-05-11 28 views
0

在asp.net web api上工作。有一个自定义对象,需要从这个对象的JSON。我的对象是下面的。 enter image description here在web api中如何自定义对象到json字符串

正如你看到的上面画线类,如:oUserEntity,UserHomeLink,首页 现在我要像波纹管一个JSON。

enter image description here

寻找一个聪明的方式自定义对象为JSON像上面

回答

0

试试这个

public class Main 
     { 
     public string mainName { get; set; } 
     public List<Child1> Child1List { get; set; } 

      public Main() 
      { 
      this.Child1List = new List<Child1>(); 
      } 
     } 
     public class Child1 
     { 
      public int childId1 { get; set; } 
      public List<Child2> ChildList2 { get; set; } 

      public Child1() 
      { 
      this.ChildList2 = new List<Child2>(); 
      } 
     } 

     public class Child2 
     { 
      public int childId2 { get; set; } 
     } 
     public partial class display : System.Web.UI.Page 
     { 
       Dictionary<string, List<object>> result = 
       new Dictionary<string, List<object>>(); 

     protected void Page_Load(object sender, EventArgs e) 
     { 
      var child2List = new List<Child2>(); 
      for (int i = 0; i < 2; i++) 
      { 
       child2List.Add(new Child2() { childId2 = i }); 
      } 

      var child1 = new List<Child1>(); 
      for (int i = 0; i < 2; i++) 
      { 
       var child = new Child1(); 
       child.childId1 = i; 
       child.ChildList2.Add(child2List[i]); 
       child1.Add(child); 
      }  

      var main = new Main(); 
      main.mainName = "hi"; 
      main.Child1List = child1; 
      this.FormatObjects(main); 
      var josn = JsonConvert.SerializeObject(this.result); 
     } 

     private void FormatObjects(dynamic mainObj) 
     { 
      var props = mainObj.GetType().GetProperties(); 
      dynamic child = null; 

      foreach (PropertyInfo item in props) 
      { 
       if (item.PropertyType.IsGenericType) 
       { 
       child = item.GetValue(mainObj); 
       item.SetValue(mainObj, Convert.ChangeType(null, item.PropertyType), null); 
       } 
      } 
      this.AddResult(mainObj); 

      if (child != null) 
      { 
       foreach (var item in child) 
       { 
       this.FormatObjects(item); 
       } 
      } 
     } 

     private void AddResult(dynamic mainObj) 
     { 
      string key = mainObj.GetType().Name; 
      if (result.ContainsKey(key)) 
      { 
      this.result[key].Add(mainObj); 
      return; 
      } 

      var value = new List<object>(); 
      value.Add(mainObj); 
      this.result.Add(key, value); 
     } 
    } 

这将导致,您可以重命名类,并添加属性

{"Main":[{"mainName":"hi","Child1List":null}], 
"Child1":[{"childId1":0,"ChildList2":null},{"childId1":1,"ChildList2":null}], 
"Child2":[{"childId2":0},{"childId2":1}]} 
相关问题