问题
I'm trying to use the geocoding code from here in my ASP.NET MVC 2 site. Unfortunately, some of that code, specifically the DataContractJsonSerializer usage, is only possible through .NET 4.0. As my hosting provider doesn't support .NET 4, I'm forced to implement that functionality in .NET 3.5.
How can I rework the code (which I have reposted below) to work in .NET 3.5?
The Google Maps Geocoding API can also return XML, if that's easier to serialize in 3.5...
Below is the code I'm trying to convert from .NET 4 to .NET 3.5:
using System;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Net;
using System.Web;
.
.
.
private static GeoResponse CallGeoWS(string address)
{
string url = string.Format(
"http://maps.google.com/maps/api/geocode/json?address={0}®ion=dk&sensor=false",
HttpUtility.UrlEncode(address)
);
var request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(GeoResponse));
var res = (GeoResponse)serializer.ReadObject(request.GetResponse().GetResponseStream());
return res;
}
[DataContract]
class GeoResponse
{
[DataMember(Name="status")]
public string Status { get; set; }
[DataMember(Name="results")]
public CResult[] Results { get; set; }
[DataContract]
public class CResult
{
[DataMember(Name="geometry")]
public CGeometry Geometry { get; set; }
[DataContract]
public class CGeometry
{
[DataMember(Name="location")]
public CLocation Location { get; set; }
[DataContract]
public class CLocation
{
[DataMember(Name="lat")]
public double Lat { get; set; }
[DataMember(Name = "lng")]
public double Lng { get; set; }
}
}
}
}
回答1:
What is the specific problem that you're hitting?
Without more details it's difficult to diagnose the exact problem, but DataContractJsonSerializer
is available in .NET 3.5 - you'll need to manually add a reference to System.ServiceModel.Web.dll.
(Note that the MSDN documentation misleadingly states that DataContractJsonSerializer
can be found in System.Runtime.Serialization.dll. While this is true for .NET 4, the .NET 3.5 version of DataContractJsonSerializer
actually lives in System.ServiceModel.Web.dll.)
来源:https://stackoverflow.com/questions/3178218/using-the-wcf-datacontractjsonserializer-in-net-3-5