为什么JsonConvert.DeserializeObject会更改String值?

时间:2014-04-19 12:17:44

标签: c# json rest asp.net-web-api json.net

我从REST Web Api获得了正确的结果,但是当我尝试反序列化结果时,它将字符串值“ 034342323 ”更改为“ 7455955

我的班级

public class DataModel
     {

         public int Id { get; set; }

         public string ABN { get; set; }

         public string AccountNumber { get; set; }

     }

JSON结果

[{"Id":1,"ABN":"9949876532","AccountNumber":"034342323"}]

致电代码

 using (HttpResponseMessage response = await client.GetAsync(url).ConfigureAwait(false))
                {
                    if (response.IsSuccessStatusCode)
                    {
                        var result = await response.Content.ReadAsStringAsync();

                        result = result.Replace("\"", string.Empty).Trim();
                        result = result.Replace("\\", string.Empty).Trim();

                        var data = JsonConvert.DeserializeObject<IEnumerable<DataModel>>(result);

                      [...]


                    }

所有值保持不变,接受AccountNumber自动更改

enter image description here

注意:我们发现是否有任何字符串以“0”开头,在反序列化过程中它会自动更改!!!!

现在它变成了

[{"Id":1,"ABN":"9949876532","AccountNumber":"7455955"}]

其他

如果我不删除“”,则无法取消预期&amp;抛出错误

{"Error converting value \"[{\"Id\":1,\"ABN\":\"9949876532\",\"AccountNumber\":\"034342323\"}]\" to type 'System.Collections.Generic.IEnumerable`1[DataModel]'
  . Path '', line 1, position 174."}

        Could not cast or convert from System.String to System.Collections.Generic.IEnumerable`1[DataModel].

解决方案

   result = result.Replace("\"", "").Trim();
   result = result.Replace("\\", "'").Trim(); //This line is the tricks

感谢Andrew 的解释。所以我通过微小的修改来克服这个问题。

1 个答案:

答案 0 :(得分:2)

此行为是设计使然:整数字符串以&#34; 0&#34;将被Json.Net视为八进制数(octal 34342323 == decimal 7455955):

http://json.codeplex.com/workitem/22097

生成json时,请查看添加AccountNumber的代码,确保删除了引导"0"