Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何高效地从C#中的流中获取JSON主体?_C#_Json_Deserialization_Utf8json - Fatal编程技术网

如何高效地从C#中的流中获取JSON主体?

如何高效地从C#中的流中获取JSON主体?,c#,json,deserialization,utf8json,C#,Json,Deserialization,Utf8json,我正在使用Utf8 json库,使用JsonSerializer类的DeserializeAsync方法反序列化我的json。有时我看到它抛出异常- Arithmetic operation resulted in an overflow. 因此,我的JSON数据的值太大,无法放入对象的某个属性中,从而导致了此溢出异常。下面是我试图打印json时得到的代码,这是错误的,导致了这个算术溢出错误,但每当发生此异常时,它都不会记录该json using (var content = httpResp

我正在使用Utf8 json库,使用
JsonSerializer
类的
DeserializeAsync
方法反序列化我的json。有时我看到它抛出异常-

Arithmetic operation resulted in an overflow.
因此,我的JSON数据的值太大,无法放入对象的某个属性中,从而导致了此溢出异常。下面是我试图打印json时得到的代码,这是错误的,导致了这个
算术溢出
错误,但每当发生此异常时,它都不会记录该json

using (var content = httpResponseMessage.Content)
{
    if (content == null) return (default(T), statusCode);

    using (var responseStream = await httpResponseMessage.Content.ReadAsStreamAsync())
    {
        try
        {
            deserializedValue = await JsonSerializer.DeserializeAsync<T>(responseStream, formatResolver);
        }
        catch (Exception ex)
        {
            var bodyString = (ex as JsonParsingException)?.GetUnderlyingByteArrayUnsafe();
            var error = (bodyString != null) ? $"Bad json: {Encoding.UTF8.GetString(bodyString)}" : "Cannot Deserialize JSON";
            logger.logError(error, ex.Message, "Deserialization Exception", ex.StackTrace, (int)statusCode);
            return (default(T), HttpStatusCode.BadRequest);
        }
    }
}
使用(var content=httpResponseMessage.content)
{
if(content==null)返回(默认值(T),状态码);
使用(var responseStream=await httpResponseMessage.Content.ReadAsStreamAsync())
{
尝试
{
deserializedValue=等待JsonSerializer.DeserializeAsync(responseStream,formatResolver);
}
捕获(例外情况除外)
{
var bodyString=(例如JsonParsingException)?.GetUnderlyingByteArrayUnsafe();
var error=(bodyString!=null)?$“错误的json:{Encoding.UTF8.GetString(bodyString)}”:“无法反序列化json”;
logger.logError(错误,例如消息,“反序列化异常”,例如StackTrace,(int)状态代码);
返回(默认值(T),HttpStatusCode.BadRequest);
}
}
}
出于某种原因,
bodyString
每当发生此异常时都将显示为null,这就是为什么我的条件没有得到计算以获得JSON主体的原因。我的理解是,它将抛出
JsonParsingException
,但看起来它正在抛出其他异常

每当发生此异常时,是否有任何方法获取JSON正文?或者可以用一种更好的方式编写它,以便在异常发生时高效地获取JSON

  • 您编写了一个“算术溢出”错误,因此捕获中的实际异常类型可能是
    OverflowException
    ,而不是
    JsonParsingException

  • 我想您应该从
    responseStream
    获取
    bodyString
    。您可以使用
    responseStream.Position=0重置流,并将正文作为字节数组从中读取


  • 谢谢你的第一点,我会看一看,但混淆了你的第二点。你能举个例子说明如何有效地做吗?你可以使用MemoryStream。该技术已在中描述。