1
我正在尋找一種方法來更改屬性的名稱,當它被編碼爲JSON,其工作方式類似於DisplayAttribute
可用於更改它的顯示名稱。使用Json.Encode()序列化對象時更改成員名稱
例如,如果我編碼以下類JSON字符串
public class LatLng
{
public double Latitude { get; set; }
public double Longitude { get; set; }
}
string result = Json.Encode(new LatLng{ Latitude = 10, Longitude = 20 });
的結果將是:{"Latitude":10,"Longitude":20}
有用來創建一個JsonNameAttribute
添加到類的每個屬性的方式,如下所示
public class LatLng
{
[JsonName("lat")]
public double Latitude { get; set; }
[JsonName("lng")]
public double Longitude { get; set; }
}
string result = Json.Encode(new LatLng{ Latitude = 10, Longitude = 20 });
所以結果會是:{"lat":10,"lng":20}
?
這樣做可以不創建我自己的JSON序列化程序?