【问题标题】:Deserialize two properties into one .NET property将两个属性反序列化为一个 .NET 属性
【发布时间】:2019-02-11 03:25:59
【问题描述】:

我有一个这样的 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 对象的经度和纬度属性

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

【问题讨论】:

  • 我喜欢@qntmfred 建议 +1。这个问题让我相信你给一个简单的应用程序增加了不必要的复杂性
  • 你说得对,直到@qntmfred 扩展它,我才理解这个建议。谢谢

标签: c# json.net deserialization


【解决方案1】:

这不是你问的,但你可以这样定义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;
        }
    }
}

【讨论】:

  • 我已经添加了几行试图更好地解释自己
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多