J#字符串中的C#Json字符串

时间:2014-08-05 13:30:07

标签: c# json

我对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\"}"}

任何人都可以指出我可以如何解决这个问题吗?我假设有一个反斜杠意味着它忽略了引号?

由于

1 个答案:

答案 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"}}