问题描述
我有一个包含电子邮件地址和状态数据成员的类对象的列表.我正在尝试将它们转换为json,以确保在数组上有"operations"字样.
I have a List of class objects that have email address and status data members. I am trying to convert these to a json, making sure to have the "operations" word on the array.
这是我的课程:
class MyClass
{
public string email {get; set; }
public string status { get; set; }
}
这是我当前的代码(不是建筑物):
This is my current code (not building):
List<MyClass> data = new List<MyClass>();
data = MagicallyGetData();
string json = new {
operations = new {
JsonConvert.SerializeObject(data.Select(s => new {
email_address = s.email,
status = s.status
}))
}
};
这是我要获取的JSON:
This is the JSON I am trying to get:
{
"operations": [
{
"email_address": "[email protected]",
"status": "good2go"
},
{
"email_address": "[email protected]",
"status": "good2go"
},...
]
}
EDIT1 我应该提到,我为此获得的数据来自数据库.我正在从数据库中反序列化JSON,并以几种不同的方式使用数据,因此无法更改类的成员名称.
EDIT1I should mention that the data I am getting for this comes from a DB. I am de-serializing a JSON from the DB and using the data in several different ways, so I cannot change the member names of my class.
推荐答案
我相信这会给您您想要的东西.如果可能,您将不得不更改类的属性名称-
I believe this will give you what you want. You will have to change your class property names if possible -
class MyClass
{
public string email_address { get; set; }
public string status { get; set; }
}
List<MyClass> data = new List<MyClass>() { new MyClass() { email_address = "[email protected]", status = "good2go" }, new MyClass() { email_address = "[email protected]", status = "good2go" } };
var json = JsonConvert.SerializeObject(new
{
operations = data
});
这篇关于将对象列表转换为json数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!