Skip to main content
 首页 » 编程设计

c#之将两个属性反序列化为一个 .NET 属性

2024年02月20日11wayfarer

我有一个像这样的 json 响应

{ latitude: 30.4848, longitude: -70.5484 } 

现在我这样做是为了使用 newtonsoft JSON.NET 反序列化

JsonConvert.DeserializeObject<Test>(json); 

反序列化为

[JsonObject(MemberSerialization.OptIn)] 
public class Test 
{ 
    [JsonProperty(PropertyName = "longitude")] 
    public double Longitude{ get; set; } 
 
    [JsonProperty(PropertyName = "latitude")] 
    public double Latitude { get; set; } 
} 

我想将纬度和经度反序列化为 GeoCoordinate 对象的 Longitude 和 Latitude 属性

public class Test 
{ 
    public GeoCoordinate Location{ get; set; } 
} 

请您参考如下方法:

这与您的要求不完全相同,但您可以像这样定义 Location

[JsonObject(MemberSerialization.OptIn)] 
public class Test 
{ 
    private GeoCoordindate _location; 
 
    [JsonProperty(PropertyName = "longitude")] 
    public double Longitude{ get; set; } 
 
    [JsonProperty(PropertyName = "latitude")] 
    public double Latitude { get; set; } 
 
    public GeoCoordinate Location 
    { 
        get 
        { 
            if (_location == null) 
                _location = new GeoCoordinate(Latitude, Longitude); 
 
            return _location; 
        } 
    } 
}