【发布时间】:2015-12-29 18:15:53
【问题描述】:
当我尝试从 JSON 字符串反序列化为对象时遇到异常。
Input string '46.605' is not a valid integer. Path 'LatitudeCenter'
这真的很奇怪,因为JsonConvert 试图将属性反序列化为整数,但它实际上是双精度而不是整数。
我已经签入了我的 Web API 项目。我的类中的属性是双属性,在 web 项目中是相同的。
我在我的 web asp 项目中使用的代码:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("myWebApiHostedUrl");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Get the response
HttpResponseMessage response = await client.GetAsync("api/NewMap/?SouthLatitude=46.600&WestLongitude=7.085&NorthLatitude=46.610&EastLongitude=7.095&Width=900&Height=900&isVoxelMap=true");
string jsonData = response.Content.ReadAsStringAsync().Result;
//Exception here
NewMap dataMewMap = JsonConvert.DeserializeObject<NewMap>(jsonData, new JsonSerializerSettings() { Culture = CultureInfo.InvariantCulture,FloatParseHandling= FloatParseHandling.Double });
}
这是我的课:
public class NewMap
{
// ...
public double LatitudeCenter { get; set; }
public double LongitudeCenter { get; set; }
// ...
}
我的 JSON 内容:
{
// ...
"LatitudeCenter":46.605,
"LongitudeCenter":7.09,
"SouthLatitude":46.6,
"ImageBingUrl":null,
"PercentEnvironement_Plain":0,
// ...
}
【问题讨论】:
-
我们可以看看您尝试反序列化的一些 json 吗?
-
当然,谢谢。我现在添加它
-
仅使用部分
NewMap合约、您的JSON 输入以及代码的最后一行,一切对我来说都很好。这里没有问题。浮点数被正确识别,没有错误。 -
您的区域设置是否使用点以外的内容? msdn.microsoft.com/en-us/library/994c0zb1(v=vs.110).aspx
-
谢谢大家!!我找到了。因为我试图像@Aybe 所说的那样使用特定的 CultureInfo 。您可以将其添加为答案吗?
标签: c# json asp.net-web-api double deserialization