Json.NET returns empty objects serializing list of Android.Gms.Maps.Model.LatLng objects

前端 未结 2 801
攒了一身酷
攒了一身酷 2021-01-15 18:05

While serializing MapRoute object I got JSON data like this:

\"{\\\"RouteName\\\":\\\"route1\\\",\\\"RouteWaypoints\\\":[{},

2条回答
  •  太阳男子
    2021-01-15 18:38

    I believe Android.Gms.Maps.Model.LatLng is actually a Managed Callable Wrapper proxy for Google APIs for Android's LatLng. Possibly (I cannot test it myself) Json.NET's reflection mechanism is unable to successfully discover the members of such a wrapper type.

    If so, the easiest workaround would be to introduce a Data Transfer Object, map the LatLng to the DTO, and serialize that. First, define your types as follows:

    // Required for For System.Linq.Enumerable.Select
    // https://developer.xamarin.com/api/member/System.Linq.Enumerable.Select%7BTSource,TResult%7D/p/System.Collections.Generic.IEnumerable%7BTSource%7D/System.Func%7BTSource,TResult%7D/
    using System.Linq;  
    
    public class LatLngDTO
    {
        public double Latitude { get; set; }
        public double Longitude { get; set; }
    
        public static implicit operator LatLng(LatLngDTO latLng)
        {
            if (latLng == null)
                return null;
            return new LatLng(latLng.Latitude, latLng.Longitude);
        }
    
        public static implicit operator LatLngDTO(LatLng latLng)
        {
            if (latLng == null)
                return null;
            return new LatLngDTO { Latitude = latLng.Latitude, Longitude = latLng.Longitude };
        }
    }
    
    public class Id
    {
        [JsonProperty(PropertyName = "$oid")]
        public string id { get; set; }
    }
    
    public class MapRoute
    {
        public Id _id { get; set; }
        public string RouteName { get; set; }
        public List RouteWaypoints { get; set; }
    }
    

    Then, construct your MapRoute as follows:

    _mapRoute.RouteWaypoints = (_wayPoints == null ? null : _wayPoints.Select(l => (LatLngDTO)l).ToList());
    

提交回复
热议问题