我将尝试将我的复杂.NET对象转换为完全不同的JSON对象。基本上,我有一个对象数组,可以是任何派生自我的基类的类型,并且我想将该对象数组转换为我的自定义JSON对象。我认为我不能只调用简单的JsonConvert.Serialize()方法,因为我的JSON对象结构不同。
这是我.NET类的模拟:
显然这只是我真实类结构的简单视图,但希望能为我提供一些转换方法,使我能够转换我的真实类。基本上,我的类(A、B、C)将包含一组类(X、Y、C)。
假设我有一个包含以上对象的数组/集合:
我想将我的对象'myObjects'序列化为一个JSON结构,类似于这样:
这是我.NET类的模拟:
public abstract class A
{
public string Id { get; set; }
public string Title { get; set; }
public bool Enabled { get; set; }
public List<X> MyCollection { get; set; }
}
public class B : A
{
public string Foo { get; set; }
}
public class C : A
{
public int Bar { get; set; }
}
public abstract class X
{
public string Id { get; set; }
public string Title { get; set; }
public bool Enabled { get; set; }
}
public class Y : X
{
public string Hello { get; set; }
}
public class Z : X
{
public string World { get; set; }
}
显然这只是我真实类结构的简单视图,但希望能为我提供一些转换方法,使我能够转换我的真实类。基本上,我的类(A、B、C)将包含一组类(X、Y、C)。
假设我有一个包含以上对象的数组/集合:
List<A> myObjects = new List<A>();
A myVar = new B();
myVar.Title = "Number 1";
myVar.MyCollection.Add(new Y());
myVar.MyCollection.Add(new Y());
myVar.MyCollection.Add(new Z());
myObjects.Add(myVar);
myVar = new B();
myVar.Title = "Number 2";
myVar.MyCollection.Add(new Z());
myObjects.Add(myVar);
myVar = new C();
myVar.Title = "Number 3";
myVar.MyCollection.Add(new Y());
myVar.MyCollection.Add(new Y());
myObjects.Add(myVar);
我想将我的对象'myObjects'序列化为一个JSON结构,类似于这样:
[
{
name: "Number 1", //This is the value of A.Title
type: "B", //This is a NEW property I want to add to the JSON
enabled: true, //This is the value of A.Enabled
foo: "SomeValue", //This is the value of B.Foo
myCollection: [
{ name: "Y1", type: "Y", enabled: true, hello: "SomeValue" }
{ name: "Y2", type: "Y", enabled: true, hello: "SomeOtherValue" }
{ name: "Z1", type: "Z", enabled: true, world: "SomeValue" }
]
},
{
name: "Number 2",
type: "B",
enabled: true,
foo: "SomeValue",
myCollection: [
{ name: "Z2", type: "Z", enabled: true, world: "SomeValue" }
]
},
{
name: "Number 3",
type: "C",
enabled: true,
bar: "SomeValue",
myCollection: [
{ name: "Y3", type: "Y", enabled: true, hello: "SomeValue" }
{ name: "Y4", type: "Y", enabled: true, hello: "SomeOtherValue" }
]
}
]
基本上,我想在JSON中添加自己的属性并对其进行不同于我的.NET对象反映的结构化。还有一些其他我想要添加到我的对象中的属性,但它们没有列在这里(可能会使此帖子更大)。我基本上只需要一种方法来以自己的定制方式序列化我的对象。我需要确保我序列化派生类型,以便可以携带某些属性。有谁可以帮助我指导如何解决这个问题?
return Json(myObjects);
,但您需要根据所需的预期结果对myObjects进行建模。 - Kaizen Programmer