0

以下代码在语句中引发错误:

Result res = (Result)stdserialize.ReadObject(ms);

错误是:反序列化 TrackLocation.MainPage+Result 类型的对象时出错。应来自命名空间“”的结束元素“类型”。从命名空间“”中找到元素“项目”。

HttpClient gClientRequest = new HttpClient();
System.Uri gURI = new Uri("http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true");
HttpResponseMessage gResponse = await gClientRequest.GetAsync(gURI);
string   strStream = await gResponse.Content.ReadAsStringAsync();
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(strStream));
DataContractJsonSerializer stdserialize = new DataContractJsonSerializer(typeof(Result));
Result res = (Result)stdserialize.ReadObject(ms);

//############################################### ##############################################

[DataContract]
public class Address
{
    [DataMember(Name = "long_name")]
    public string address1;
    [DataMember(Name = "short_name")]
    public string shortaddress;
    [DataMember(Name = "formatted_address")]
    public string formattedtaddress;
    [DataMember(Name = "lat")]
    public string latitude;
    [DataMember(Name = "long")]
    public string latitude;
}
//###############################################################################################



[DataContract]
    public class Result
    {           

        [DataMember(Name = "results")]
        public Address[] Results { get; set; }

        [DataMember(Name = "status")]
        public string Status { get; set; }
    }

    [DataContract]
    public class Address
    {
        [DataMember(Name = "formatted_address")]
        public string FormattedAddress;

        [DataMember(Name = "address_components")]
        public AddressComponent[] AddressComponents;
    }

    [DataContract]
    public class AddressComponent
    {
        [DataMember(Name = "long_name")]
        public string LongName;

        [DataMember(Name = "short_name")]
        public string ShortName;

        [DataMember(Name = "types")]
        public string Types;
    }

任何想法如何解决这个问题。任何帮助将不胜感激。

4

2 回答 2

0

仔细看看 JSON,你的Type字段AddressComponent应该string[]不是string.

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "285",
               "short_name" : "285",
               "types" : [ "street_number" ]
            },

此外,您似乎有两个Address类和一个result(小写)和Result(大写)类;我假设这些是剪切和粘贴问题,因为它们似乎与返回的 JSON 不匹配。

于 2012-11-27T07:41:08.600 回答
0

我刚刚将 JSON 转换为 XMl 并发现要重复的类型(检查下面的屏幕截图)但在您的数据合同中它的 [DataMember(Name = "types")] public string Types;

把它当作

        [DataMember(Name = "types")]
        public string[] Types;

它应该可以工作 截屏

于 2012-11-27T19:19:26.353 回答