我会尽力解释这个问题。我有一个名为Prospect的类,其中包含电子邮件,公司,名字,姓氏,电话的字符串。
我要求以JSON格式输出JSON中的Prospect信息
[
{"email":"[email protected]",
"properties":[
{
"property":"company",
"value": "Company Name"
},
"property":"firstname",
"value":"John"
},
"property":"surname",
"value":"Smith"
},
"property":"phone",
"value":"01234567891"
}]
}
]
我需要输出我捕获的所有潜在客户的JSON。我通过创建一个Customer类来尝试这个:
public class Customer
{
public string email { get; set; }
public List<Property> properties { get; set; }
}
和一类财产:
public class Property
{
public string property { get; set; }
public string value { get; set; }
}
我不能为我的生活得到我追求的结果。我认为它是Customer类中的Property列表。如果我将List更改为字符串并在此处仅定义一个值,则输出正常。
请帮忙 :(
此代码有效:
public class Property
{
public string property { get; set; }
public string value { get; set; }
}
public class Customer
{
public string email { get; set; }
public List<Property> properties { get; set; }
}
static void Main(string[] args)
{
string JSON = @"[
{""email"":""test @test.com"",
""properties"":[
{
""property"":""company"",
""value"": ""Company Name""
},
{ ""property"":""firstname"",
""value"":""John""
},
{ ""property"":""surname"",
""value"":""Smith""
},
{ ""property"":""phone"",
""value"":""01234567891""
}]
}
]
";
Customer[] obj = JsonConvert.DeserializeObject<Customer[]>(JSON);
}
请注意:1。我必须在属性元素中添加缺少的开头{
括号。
[解决了]
感谢所有提供意见的人。您的指导帮助我解决了我的问题。
public class Customer
{
public string email { get; set; }
public List<Property> properties { get; set; }
}
public class Property
{
public string property { get; set; }
public string value { get; set; }
}
private void button1_Click(object sender, EventArgs e)
{
Customer _c = new Customer();
_c.email = email.Text;
_c.properties = new List<Property>();
_c.properties.Add(new Property{ property = "company", value = company.Text });
_c.properties.Add(new Property { property = "website", value = website.Text });
_c.properties.Add(new Property { property = "firstname", value = firstname.Text });
_c.properties.Add(new Property { property = "lastname", value = lastname.Text });
_c.properties.Add(new Property { property = "phone", value = phone.Text });
string json = JsonConvert.SerializeObject(_c, Formatting.Indented);
outputBox.Text = json;
}