[英]Geoposition deserialization error (Newtonsoft.Json) -2146233088
我正在嘗試在Windows Phone(WinRT)應用程序中反序列化Geoposition
對象,但出現此Exception
:
-2146233088,消息:“無法找到用於
Windows.Devices.Geolocation.Geoposition
類型的構造函數。類應具有默認構造函數,一個帶參數的構造函數或帶有JsonConstructor屬性標記的構造函數。路徑'CivicAddress'” 。
Geoposition
與Newtonsoft Json.NET不兼容嗎? 如果不是這樣,我可以使用一些幫助找到解決方法。
下面的代碼片段顯示了引發異常的位置。
public async void Sample()
{
Geolocator geo = new Geolocator();
geo.DesiredAccuracyInMeters = 50;
var x = await geo.GetGeopositionAsync();
Geoposition geo = JsonConvert.DeserializeObject<Geoposition>(CurrentContext.LocationAsString);
await EventMap.TrySetViewAsync(geo.Coordinate.Point, 18D);
}
似乎Geoposition
僅具有只讀屬性,並且沒有將這些屬性的值用作構造函數參數的公共構造函數。 因此,您可以序列化它,但不能在反序列化期間構造它。
解決方法您可以做的是構造您自己的此類的版本,專門用於序列化目的,僅包括應用程序中實際需要的那些屬性。
例如,如果如您的問題中所示,僅需要序列化Geoposition.Coordinate.Point
字段,則可以執行以下操作:
namespace YourAppNameSpaceHere
{
using Windows.Devices.Geolocation;
public class SerializableGeoPoint
{
public SerializableGeoPoint(Geoposition location)
: this(location.Coordinate.Point) {}
public SerializableGeoPoint(Geopoint point)
{
this.AltitudeReferenceSystem = point.AltitudeReferenceSystem;
this.GeoshapeType = point.GeoshapeType;
this.Position = point.Position;
this.SpatialReferenceId = point.SpatialReferenceId;
}
[JsonConverter(typeof(StringEnumConverter))]
public AltitudeReferenceSystem AltitudeReferenceSystem { get; set; }
[JsonConverter(typeof(StringEnumConverter))]
public GeoshapeType GeoshapeType { get; set; }
[JsonProperty]
public BasicGeoposition Position { get; set; }
[JsonProperty]
public uint SpatialReferenceId { get; set; }
public Geopoint ToWindowsGeopoint()
{
return new Geopoint(Position, AltitudeReferenceSystem, SpatialReferenceId);
}
}
}
序列化時,您可以執行以下操作:
Geoposition position = ....; // call to get position.
CurrentContext.LocationAsString = JsonConvert
.SerializeObject(new SerializableGeoPoint(position));
反序列化為:
var locationPoint = JsonConvert
.DeserializeObject<SerializableGeoPoint>(CurrentContext.LocationAsString)
.ToWindowsGeopoint();
您可能需要在應用程序啟動期間的某個地方為序列化設置添加此設置,在此您可以對應用程序執行其他一次性初始化。
JsonConvert.DefaultSettings = (() =>
{
var settings = new JsonSerializerSettings();
settings.Converters.Add(new StringEnumConverter());
return settings;
});
它指定JSON序列化的默認設置,在這種情況下,添加知道如何在枚舉和字符串之間轉換的轉換器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.