2

I am uploading a .json file from my local drive:

using (WebClient client = new WebClient())
{
    client.Headers.Add("Content-Type", "application/json");

    byte[] resp = client.UploadFile("http://mycoolWebsite.com", "POST", "path to file");

    string textResponse = System.Text.Encoding.ASCII.GetString(resp)

}

The response from client.UploadFile is of type byte[] when I want it to be json so I can more easily parse through it. How can I ask the server to give me back json?

user3772119
  • 484
  • 3
  • 7
  • 16
  • 3
    You generally can't influence server side code - whatever server feels to return it will return. Some requests accept ["accept"](http://en.wikipedia.org/wiki/List_of_HTTP_headers) header - you can try that to see if that particular server gives different responses. – Alexei Levenkov Jun 27 '14 at 16:39
  • 1
    it is not related to server side code. `UploadFile` returns `byte[]` instead of string. What you do is correct (If your server uses ASCII encoding, but I would use UTF8). – L.B Jun 27 '14 at 16:42
  • The body of the response will be in what ever format the server you are uploading to decides it should be. – Mike Cheel Jun 27 '14 at 16:44
  • I'm positive the response is json but how do I parse through it as json? I.e. response = `"ball":123, 543, 543, "stuff": [1, 2, 3]"` and I want to find `ball:543`? – user3772119 Jun 27 '14 at 17:23

1 Answers1

2

The method is defined as returning byte[] with good reason. It allows the method to be used with any web service and return back the raw response from the server. Defining server-side response is the responsibility of the server (obviously). Your best bet is to take the raw response, encode it as text (as you're doing), and then check to see if the response contains well-formed JSON, allowing you to re-encode as JSON and parse at that time.

The response will be whatever the server returns; it's up to you to handle it.

Community
  • 1
  • 1
jcasner
  • 325
  • 3
  • 14
  • I know the response contains JSON, as I have done this in Powershell. So `var jsonOutput = System.Text.Encoding.ASCII.GetString(resp).JsonConvert()` ? – user3772119 Jun 27 '14 at 16:58
  • To get a generic .NET object. var myObject = JsonConvert.DeserializeObject(System.Text.Encoding.ASCII.GetString(resp)). If you create an object that is of the response type you could do JsonConvert.DeserializeObject<[YourObjectType]>(). You could also do JObject.Parse(System.Text.Encoding.ASCII.GetString(resp)) if you want to use Json.Linq. This can be easier if your just after some specific value or values in the response. You just query for them using linq. – cgotberg Jun 27 '14 at 18:04