简体   繁体   English

ReadAsAsync Json反序列化

[英]ReadAsAsync Json Deserialization

I have run into a problem with using ReadAsAsync to deserialize as list of objects from JSON being returned from a web service. 我遇到了使用ReadAsAsync反序列化作为从Web服务返回的JSON对象列表的问题。 The resulting list has the correct number of records, but all the properties on the objects are null. 结果列表具有正确的记录数,但是对象上的所有属性均为空。 The strange thing is that the same code works fine for my co-workers, and the code works ok for me in other solutions. 奇怪的是,相同的代码对我的同事来说很好用,而在其他解决方案中对我来说也可以。 I distilled the code down to this: 我将代码简化为:

  var response = new System.Net.Http.HttpResponseMessage();
            response.Content = new System.Net.Http.StringContent(@"{""Currency"": ""USD""}", System.Text.Encoding.UTF8, "application/json");
            var prices = response.Content.ReadAsAsync<Price>().Result;

  public class Price
    {
        public string Currency { get; set; }
    }

This will execute fine, but the Currency property will be null. 这样可以很好地执行,但是Currency属性将为null。 I tried copying this code to a blank ASP.NET MVC solution and it worked fine. 我尝试将此代码复制到空白的ASP.NET MVC解决方案中,并且工作正常。 I also tried it in both Visual Studio 2015 and 2017 and had the same problem in both. 我也在Visual Studio 2015和2017中都尝试过,但两者都存在相同的问题。

I finally found the solution to this problem. 我终于找到了解决这个问题的方法。 It had to do with the NewtonSoft.Json assembly. 它与NewtonSoft.Json程序集有关。 It appears there was a version conflict between the one in the GAC and the one used by Visual Studio. 看来GAC中的版本与Visual Studio使用的版本之间存在版本冲突。 Replacing the one in the GAC with the one from Visual Studio resolved the issue. 用Visual Studio中的一个替换GAC中的一个即可解决此问题。 Here is the article I found with this solution. 这是我在此解决方案中找到的文章。

https://billti.github.io/jsdocs/articles/troubleshooting/newtonsoft.html https://billti.github.io/jsdocs/articles/troubleshooting/newtonsoft.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM