WebAPI2-RestSharp-NewtonsoftJson反序列化在内容末尾崩溃

本文关键字:崩溃 反序列化 WebAPI2-RestSharp-NewtonsoftJson | 更新日期: 2023-09-27 18:27:01

我遇到了一个让我抓狂的问题。我使用RestSharp在WebAPI2上成功地构建了几个rest服务和客户端。突然间,我连最简单的程序都无法运行(见下文)。我目前正在尝试显式地使用Newtonsoft.JSON进行序列化和反序列化。我安装了Json库的7.0.2版本,它似乎取代了MS在VS2015中提供的6版本。我包括下面的所有代码。请注意,经Fiddler验证,服务器似乎工作正常。我确实注意到,当我开始使用Newtonsoft库时,它在所有"上添加了以前没有出现过的转义。然而,结果是一样的-它错误地指示了一个比指示的"内容长度"多1个字符的问题。

注意:我是C#的新手,但在C/C++上已经有25年以上的时间了;我确信我错过了一些愚蠢的东西,但我已经追了大约3个晚上了,没有任何运气。提前感谢!

WebAPI2配置:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace webapi2_server
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            // Web API routes
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "{controller}",
                defaults: new {  }
            );
        }
    }
}

WebAPI2控制器:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Newtonsoft.Json;
public class my_data
{
    public string sdata { get; set; }
    public int    idata { get; set;  }
}

namespace webapi2_server.Controllers
{
    public class TestController : ApiController
    {
        public HttpResponseMessage Get(HttpRequestMessage request)
        {
            HttpResponseMessage response;
            List<my_data> myTestData = new List<my_data>();
            myTestData.Add(new my_data() { sdata = "string1", idata = 1 });
            myTestData.Add(new my_data() { sdata = "string2", idata = 2 });
            myTestData.Add(new my_data() { sdata = "string3", idata = 3 });
            string json = JsonConvert.SerializeObject(myTestData,     Formatting.Indented);
            return response = request.CreateResponse(HttpStatusCode.OK, json);
        }
    }
}

客户端软件:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using RestSharp;

public class my_data
{
    public string sdata { get; set; }
    public int idata { get; set; }
}
namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            RestClient client = new RestClient();
            client.BaseUrl = new Uri("Http://192.168.0.6");
            var request = new RestRequest();
            request.Resource = "test/test";
            request.Method = Method.GET;
            request.RequestFormat = DataFormat.Json;
            List<my_data> my_data_response = new List<my_data>();
            IRestResponse<List<my_data>> response = client.Execute<List<my_data>>(request);
            my_data_response = JsonConvert.DeserializeObject<List<my_data>>(response.Content);
            System.Console.WriteLine("Response String: " + response.Content);
            System.Console.WriteLine("Item Count: " + my_data_response.Count() );
        }
    }
}

运行客户端的输出:

未处理的异常:Newtonsoft.Json.JsonSerializationException:转换值时出错[{"sdata":"字符串1","idata":1},{"sdata":"字符串2","idata":2},{"sdata":"字符串3","idata":3}]"以键入'System.Collections.Generic.List 1[my_data]'. Path '', line 1, position 205. ---> System.ArgumentException: Could not cast or convert from System.String to System.Collections.Generic.List 1[my_data]。位于Newtonsoft.Json.Utilities.ConvertUtils.EnsureTypeAssignable(对象值,类型initialType,类型targetType)位于Newtonsoft.Json.Utilities.ConvertUtils.ConvertOrCast(对象initialValue,CultureInfo区域性,类型targetType)位于Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureType(JsonReader读取器,对象值,CultureInfo区域性,JsonContract约定,类型targetType)---内部异常堆栈跟踪结束---enter code here

WebAPI2-RestSharp-NewtonsoftJson反序列化在内容末尾崩溃

我现在不使用Newtonsoft.Json,只使用MS的东西就可以了,这不是转义。然而,我也遇到了一些问题,这就是我一开始尝试使用JSOFT的原因。我看到评论说MS序列化程序与List<>有问题。。。

这对我来说没有意义——我认为如果我用Newtonsoft进行序列化和反序列化,它应该可以工作。。。

当我回到现实世界的问题时,我不确定这是否可行,但我会看看会发生什么。如果有人看到张贴的问题,请告诉我。谢谢