反序列化JSON对象时出错“解析值时遇到意外字符:

问题描述 投票:1回答:1

我正在尝试流式传输大型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);
        }
    }
}

当我从Postman调用此Web API控制器方法时,我收到以下错误

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

这段代码有什么问题?

c# json asp.net-web-api2 streaming
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.