我正在使用网络服务来获取有关路线里程的数据。然后我使用反序列化器来解析它。这是 JSON 的外观:
[{"__type":"CalculateMilesReport:http:\/\/pcmiler.alk.com\/APIs\/v1.0","RouteID":null,"TMiles":445.5]
有了这个回应,我遇到了几个问题。为什么被包装到集合中,如何设置对象模型?它还抱怨特殊的 __type 属性。所以,我做了“hack”和“prepped”字符串:
// Cut off first and last charachters [] - they send objects as arrays
rawJSON = rawJSON.Substring(1, rawJSON.Length - 2);
// Hide "__type" attribute as it messes up serializer with namespace
rawJSON = rawJSON.Replace("__type", "type");
然后一切都与这个对象一起工作:
[DataContract]
public class PCMilerResponse
{
[DataMember(Name = "Errors", EmitDefaultValue = false)]
public PCMilerError[] Errors { get; set; }
[DataMember(Name = "TMiles", EmitDefaultValue = false)]
public decimal DrivingDistance { get; set; }
}
现在我修改了对 Web 服务的调用,我得到了以下响应
[
{"__type":"CalculateMilesReport:http:\/\/pcmiler.alk.com\/APIs\/v1.0","RouteID":null,"TMiles":445.5},
{"__type":"GeoTunnelReport:http:\/\/pcmiler.alk.com\/APIs\/v1.0","RouteID":null,"GeoTunnelPoints":
[{"Lat":"34.730466","Lon":"-92.247147"},{"Lat":"34.704863","Lon":"-92.29329"},{"Lat":"34.676312","Lon":"-92.364654"},{"Lat":"29.664271","Lon":"-95.236735"}]
}
]
现在,为什么有数组和“__type”是有道理的。但我不确定如何编写对象来正确解析它。我想需要应用特殊属性,也许需要通用数组?关于如何正确反序列化它的任何帮助?
PS我可以做更多的黑客攻击并将那些字符串替换为内部有2个对象的对象,但我想知道是否有“正确”的方式来处理它。