简体   繁体   English

如何序列化以在F#上使用JSON.NET流?

[英]How serialize to stream with JSON.NET on F#?

I need to send JSON to WebResourceResponse : 我需要将JSON发送到WebResourceResponse

override this.ShouldInterceptRequest(view:WebView, request:IWebResourceRequest) =
    let rows = Customer.fakeData 1 // Array of records

    let st = Shared.jsonToStream(rows)
    new WebResourceResponse("application/javascript", "UTF-8", st)

But don't see how do that. 但是不知道怎么做。 I use Json.NET and F#. 我使用Json.NET和F#。

When I run: 当我跑步时:

let jsonToStream(value:'T) =
    let serializer = new JsonSerializer()
    let std = new IO.MemoryStream()
    let sw = new IO.StreamWriter(std)
    let json = new JsonTextWriter(sw)
    serializer.Serialize(json, value)
    //std.Position <- 0L
    std

the response returns as a blank string. 响应返回为空白字符串。

You have the following issues: 您有以下问题:

  1. You need to dispose of your StreamWriter and JsonTextWriter so that the serialized JSON is flushed to the underlying stream. 您需要处理StreamWriterJsonTextWriter以便将序列化的JSON刷新到基础流。 This can be done by replacing let with use . 这可以通过用use代替let来完成。

    However, you need to do so without closing the underlying stream std , since you are going to read from it later. 但是,您需要这样做而不关闭基础流std ,因为稍后将要从中读取它。

  2. Having done so, you need to reset the position of the std stream after sw and json have gone out of scope and been disposed. 这样做后,您需要在swjson超出范围并被处置后重置std流的位置。 If you try to reset the position before then it won't work. 如果您尝试在此之前重置位置,则它将不起作用。

Thus the following will work: 因此,以下将起作用:

let jsonToStream(value:'T) =
    let serializer = new JsonSerializer()
    let std = new IO.MemoryStream()
    (   use sw = new StreamWriter(std, new UTF8Encoding(false, true), 1024, true)
        use json = new JsonTextWriter(sw, CloseOutput = false)
        serializer.Serialize(json, value))
    std.Position <- 0L
    std

Note the use of parentheses to restrict the scope of sw and json so that std.Position can be reset after they go out of scope. 请注意使用括号来限制swjson的范围,以便在超出范围后可以重置std.Position jsonToStream(rows) will now return an open MemoryStream containing complete, serialized JSON and positioned at the beginning. jsonToStream(rows)现在将返回一个打开的MemoryStream其中包含完整的序列化JSON,并位于开头。

Sample working f# fiddle . 示例工作的小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM