2

How do I resolve a JSON response of special characters?

When I use the Postman tool with this URL, I receive valid and expected JSON.

However, when I make a HTTP request with this url within .Net, I receive a response of special characters.

The code is the following:

    let url =      String.Format(TagsUrl, pageNumber |> string)
    let client =   httpClient APIBaseAddress
    let response = client.GetAsync(url) |> Async.AwaitTask 
                                        |> Async.RunSynchronously

   if response.IsSuccessStatusCode
         then let json =   response.Content.ReadAsStringAsync() |> Async.AwaitTask |> Async.RunSynchronously
              let result = JsonConvert.DeserializeObject<Response>(json)
              let tags =   result.items |> List.ofSeq 
                                        |> List.map (fun i -> i.name)
              tags
         else []

I also tried reading the response in as a byte array but with the same result:

let url =      String.Format(TagsUrl, pageNumber |> string)
let client =   httpClient APIBaseAddress
let response = client.GetByteArrayAsync(url) |> Async.AwaitTask 
                                             |> Async.RunSynchronously

let json = Encoding.UTF8.GetString(response);

let result = JsonConvert.DeserializeObject<Response>(json)

Appendix:

[<Literal>]
let TagsUrl = "2.2/tags?page={0}&order=desc&sort=popular&site=stackoverflow&filter=!-.G.68grSaJm"

[<Literal>]
let APIBaseAddress = "https://api.stackexchange.com/"

type Item =     { name : string }
type Response = { items: Item list }
Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
Scott Nimrod
  • 11,206
  • 11
  • 54
  • 118
  • 1
    That URL returns GZipped content that must be decompressed, see https://stackoverflow.com/questions/20990601/decompressing-gzip-stream-from-httpclient-response – Alex K. Oct 30 '17 at 14:45
  • 1
    Thank you. That link you provided resolved my issue. – Scott Nimrod Oct 30 '17 at 15:24
  • 3
    Possible duplicate of [Decompressing GZip Stream from HTTPClient Response](https://stackoverflow.com/questions/20990601/decompressing-gzip-stream-from-httpclient-response) – Brock Adams Oct 30 '17 at 16:34

1 Answers1

1

You can use the Http utility from the F# Data library. The following does the trick for me:

Http.RequestString
  ( "https://api.stackexchange.com/2.2/tags" + 
    "?page=1&order=desc&sort=popular&site=stackoverflow&filter=!-.G.68grSaJm")
Tomas Petricek
  • 240,744
  • 19
  • 378
  • 553