0
在asp.net web api上工作。有一個自定義對象,需要從這個對象的JSON。我的對象是下面的。 在web api中如何自定義對象到json字符串
正如你看到的上面畫線類,如:oUserEntity,UserHomeLink,首頁 現在我要像波紋管一個JSON。
尋找一個聰明的方式自定義對象爲JSON像上面
在asp.net web api上工作。有一個自定義對象,需要從這個對象的JSON。我的對象是下面的。 在web api中如何自定義對象到json字符串
正如你看到的上面畫線類,如:oUserEntity,UserHomeLink,首頁 現在我要像波紋管一個JSON。
尋找一個聰明的方式自定義對象爲JSON像上面
試試這個
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}]}