我需要使用Newtonsoft Json(Json.Net)进行自定义序列化的帮助。我有以下课程:
public class Person
{
[JsonProperty(PropertyName = "PersonName")]
public string Name { get; set; }
[JsonIgnore]
public int Age { get; set; }
public Address PersonAddress { get; set; }
}
public class Address
{
[JsonProperty(PropertyName = "Address1")]
public string Address1 { get; set; }
[JsonIgnore]
public string Address2 { get; set; }
[JsonProperty(PropertyName = "City")]
public string City { get; set; }
[JsonProperty(PropertyName = "State")]
public string State { get; set; }
[JsonIgnore]
public string Country { get; set; }
}
当我序列化上面的类时,它应该返回如下输出:
{
"PersonName":"Name",
"Address1":"Address1",
"City":"City",
"State":"state"
}
如何使用Newtonsoft进行操作?
答案 0 :(得分:2)
您可以按如下方式创建第三个类:
public class Rootobject
{
public string PersonName { get; set; }
public string Address1 { get; set; }
public string City { get; set; }
public string State { get; set; }
}
然后,一个像这样的物体:
var rootObject = new Rootobject()
{
PersonName = person.Name,
Address1 = address.Address1,
City = address.City,
State = address.State
};
最后使用JsonCovert序列化它:
var result = JsonConvert.SerializeObject(rootObject);