我对C#比较新,我目前正在尝试使用JSON序列化一个字符串,所以它基本上是这样的:
{ "firstname": "John", "lastname": "Smith", "address": { "street": "1 Main Street", "city": "London", "postcode": "A12 3AB" } }
我目前有以下代码:
AddressValues addressStr = new AddressValues();
addressStr.street = "1 Main Street";
addressStr.city= "London";
addressStr.postcode = "A12 3AB";
string addressJson = JsonConvert.SerializeObject(addressStr);
PersonValues personDetails = new PersonValues();
personDetails.firstname = "John";
personDetails.lastname = "Smith";
personDetails.address = addressJson ;
string jsonContent = JsonConvert.SerializeObject(personDetails);
班级......
public class AddressValues
{
public string street;
public string city;
public string postcode;
}
public class PersonValues
{
public string firstname;
public string lastname;
public string address;
}
当我运行脚本时,控制台显示以下内容:
{ "firstname": "John", "lastname": "Smith", "address": "{\"street\":\"1 Main Street\", \"city\":\"London\", \"postcode\": \"AB12 3AB\"}"}
任何人都可以指出我可以如何解决这个问题吗?我假设有一个反斜杠意味着它忽略了引号?
由于
答案 0 :(得分:6)
按以下方式声明类
public class Address
{
public string street;
public string city;
public string postcode;
}
public class PersonValues
{
public string firstname;
public string lastname;
public Address address; //SEE THIS LINE
}
并用作
PersonValues personDetails = new PersonValues();
personDetails.firstname = "John";
personDetails.lastname = "Smith";
personDetails.address = new Address();
personDetails.address.street = "1 Main Street";
personDetails.address.city = "London";
personDetails.address.postcode = "A12 3AB";
string jsonContent = JsonConvert.SerializeObject(personDetails);
最后的json是
{"firstname":"John","lastname":"Smith","address":{"street":"1 Main Street","city":"London","postcode":"A12 3AB"}}