WebClient.OpenReadAsync() corrupts JSON data. Why?
I have a class in my Silverlight app that (de-)serializes JSON strings to/from an object class.
I use WebClient.OpenReadAsync
to get a file that cont开发者_运维百科ains this JSON string:
{"FirstName":"Bob","LastName":"Underwood"}
After calling OpenReadAsync
however, the retrieved string has a lot of extra characters:
"PK\n\0\0\0\0\0�u�>h��5\0\0\05\0\0\0\t\0\0\0test.json\"{\\\"FirstName\\\":\\\"Gary\\\",\\\"LastName\\\":\\\"MacDonald\\\"}\"PK\0\n\0\0\0\0\0�u�>h��5\0\0\05\0\0\0\t\0\0\0\0\0\0\0\0\0 \0\0\0\0\0\0\0test.jsonPK\0\0\0\0\0\07\0\0\0\\\0\0\0\0\0"
This is the code I'm using to download the JSON:
WebClient client = new WebClient();
client.OpenReadCompleted += client_OpenReadCompleted;
client.OpenReadAsync(new Uri("/someJsonFile.zip", UriKind.Relative));
void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) {
if (e.Error == null) {
StreamReader reader = new StreamReader(e.Result);
string jsonString = reader.ReadToEnd().ToString();
}
else {
addMessage("Error " + e.Error.ToString());
}
}
jsonString
ends up with all that extra data, so I can't deserialize it as is.
Another thing to note: the URI points to someJsonFile.zip
, but it's really not zipped, when I give the file a extension like .json
, or no extension, I get a error that it cannot find the file, but when I give it a extension like .zip
, it finds it fine. Is there a way I can use a normal or no extension? I was wondering if this was a configuration issue.
Questions:
Am I doing something wrong in pulling this file and using
StreamReader
to get the string that's causing me to get all that trash data?Do I need to do something specific to be able to use
WebClient
to grab a file with different extensions, like.json
, or even no extension at all?
1 - That data stream certainly is a ZIP (PK
is the old PKZip marker and the test.json filename is mentioned in its index as well).
Your server may be setup to serve all files compressed (or you may simply be accessing an actual zip file). Please check the server settings.
2 - As for the second question, the WebClient does not care about file types. It is just a stream of data that needs to be interpreted by something that knows what the data is (i.e. your code).
It is only the server that may be configured to serve up different files in different ways.
I was able to figure things out with my domain provider, appears to have been some configuration issues on their end.
精彩评论