反序列化JSON对象时发生错误“解析值时遇到意外字符:<。Path”,第0行,位置0。”

时间:2018-09-16 18:01:44

标签: c# json asp.net-web-api2 streaming

我正在尝试流式传输一个大的JSON文件并逐项反序列化。

我正在为此测试https://github.com/ysharplanguage/FastJsonParser/blob/master/JsonTest/TestData/fathers.json.txt使用。

这是我的代码:

using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Newtonsoft.Json.Linq;
using System.Threading.Tasks;

namespace AMServices.Controllers
{
    public class FathersData
    {
        public Father[] fathers { get; set; }
    }

    public class Someone
    {
        public string name { get; set; }
    }

    public class Father : Someone
    {
        public int id { get; set; }
        public bool married { get; set; }
        // Lists...
        public List<Son> sons { get; set; }
        // ... or arrays for collections, that's fine:
        public Daughter[] daughters { get; set; }
    }

    public class Child : Someone
    {
        public int age { get; set; }
    }

    public class Son : Child
    {
    }

    public class Daughter : Child
    {
        public string maidenName { get; set; }
    }

    public class StreamerController : ApiController
    {
        static readonly JsonSerializer _serializer = new JsonSerializer();
        static readonly HttpClient _client = new HttpClient();

        [HttpPost]
        [Route("streamer/stream")]
        public async Task<IHttpActionResult> stream()
        {
            string apiUrl = "https://github.com/ysharplanguage/FastJsonParser/blob/master/JsonTest/TestData/fathers.json.txt";

            using (var stream = await _client.GetStreamAsync(apiUrl).ConfigureAwait(false))
            using (var reader = new StreamReader(stream))
            using (var json = new JsonTextReader(reader))
            {
                if (json == null)
                    StatusCode(HttpStatusCode.InternalServerError);

                JsonSerializer serializer = new JsonSerializer();

                JObject obj = JObject.Load(json);
                // Father f = serializer.Deserialize<Father>(json);
            }

            return StatusCode(HttpStatusCode.OK);
        }
    }
}

当我从邮递员调用此WebAPI控制器方法时,出现以下错误

  

“ ExceptionMessage”:“解析值时遇到意外字符:<。路径,第0行,位置0。”,   “ ExceptionType”:“ Newtonsoft.Json.JsonReaderException”,

此代码有什么问题?

1 个答案:

答案 0 :(得分:0)