我调用了一个REST API,返回了以下JSON字符串:
"{"profile":[{"name":"city","rowCount":1,"location": ............
在反序列化之前,我尝试用以下代码删除转义符:
jsonString = jsonString.Replace(@"", " ");
但当我对它进行反序列化时,它会抛出一个input string was not in a correct format
:
SearchRootObject obj = JsonConvert.DeserializeObject<SearchRootObject>(jsonString);
以下是完整的代码:
public static SearchRootObject obj()
{
String url = Glare.searchUrl;
string jsonString = "";
// Create the web request
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
// Get response
var response = request.GetResponse();
Stream receiveStream = response.GetResponseStream();
// Pipes the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
jsonString = jsonString + readStream.ReadToEnd();
jsonString = jsonString.Replace(@"", " ");
// A C# object representation of deserialized JSON string
SearchRootObject obj = JsonConvert.DeserializeObject<SearchRootObject>(jsonString);
return obj;
}
在切换到使用JavaScriptSerializer()
反序列化JSON字符串后,我意识到我的对象中有一个int
类型property
,用于JSON字符串中的十进制值。我将int
更改为double
,这解决了我的问题。JsonConvert.DeserializeObject<>
和JavaScriptSerializer()
都处理转义符。没有必要删除转义符。我更换了以下代码:
jsonString = jsonString.Replace(@"", " ");
SearchRootObject obj = JsonConvert.DeserializeObject<SearchRootObject>(jsonString);
return obj;
带有:
return new JavaScriptSerializer().Deserialize<SearchObj.RootObject>(jsonString);