Search code examples
windows-8microsoft-metrowindows-runtimewinrt-xamlwinrt-async

Error while parsing JSON response in Windows 8


The following code throws error at statement :

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

And the error is : There was an error deserializing the object of type TrackLocation.MainPage+Result. End element 'types' from namespace '' expected. Found element 'item' from namespace ''.

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;
    }

any idea how to fix this issue.Any help would be greatly appreciated.


Solution

  • I just converted the JSON to XMl and found the types to be repeated(check screen shot below) but in your datacontract its [DataMember(Name = "types")] public string Types;

    Just put this as

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

    and it should work Screen shot