使用JSON.net写入HttpClient请求流

时间:2017-09-25 20:36:16

标签: c# json

我有一些相当大的json要发送邮件请求到Api。

使用C#(Xamarin)我想将这个Json直接写入请求流。

我已尝试实施自定义HttpContent,但我要么无法从封闭的流中读取'例外(当我使用处置时)或空身。

请不要建议使用PushStreamContent ,我在Xamarin中无法访问它,我也希望了解这一点。

e.g:

public class JsonContent : HttpContent
{
    public object SerializationTarget { get; private set; }
    public JsonContent(object serializationTarget)
    {
        SerializationTarget = serializationTarget;
        this.Headers.ContentType = new MediaTypeHeaderValue("application/json");
    }
    protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)
    {
        using (StreamWriter writer = new StreamWriter(stream))
        using (JsonTextWriter jsonWriter = new JsonTextWriter(writer))
        {
            JsonSerializer ser = new JsonSerializer();
            ser.Serialize(jsonWriter, SerializationTarget);
        }



    // Should I dispose here or not ? When I do, the stream is 'closed'

    // When I do not dispose, the body seems to be empty

    // Should I Wrap this in a await Task.Run(() => {});
    // To make it 'async'






    }

    protected override bool TryComputeLength(out long length)
    {
        //we don't know. can't be computed up-front
        length = -1;
        return false;
    }
}

修改

在摆弄后,我得到了以下内容:

public class JsonContent : HttpContent
{
    public object SerializationTarget { get; private set; }
    public JsonContent(object serializationTarget)
    {
        SerializationTarget = serializationTarget;
        this.Headers.ContentType = new MediaTypeHeaderValue("application/json");
    }
    protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)
    {
        JsonSerializer ser = new JsonSerializer();

        StreamWriter writer = new StreamWriter(stream);
        JsonTextWriter jsonWriter = new JsonTextWriter(writer);
        ser.Serialize(jsonWriter, SerializationTarget);
        await jsonWriter.FlushAsync();
    }

    protected override bool TryComputeLength(out long length)
    {
        //we don't know. can't be computed up-front
        length = -1;
        return false;
    }
}

虽然我还没有得到为什么我需要Flush并且不能处理作家。

查看documentation

 Product product = new Product();
 product.ExpiryDate = new DateTime(2008, 12, 28);

 JsonSerializer serializer = new JsonSerializer();
 serializer.Converters.Add(new JavaScriptDateTimeConverter());
 serializer.NullValueHandling = NullValueHandling.Ignore;

 using (StreamWriter sw = new StreamWriter(@"c:\json.txt"))
 using (JsonWriter writer = new JsonTextWriter(sw))
 {
     serializer.Serialize(writer, product);
     // {"ExpiryDate":new Date(1230375600000),"Price":0}
 }

0 个答案:

没有答案