issharp
issharp

Reputation: 320

JSON Deserialization in C# error

I'm trying to deserialize some JSON in C#, but when I run my program I'm getting this error message:

enter image description here

I've looked through all my code, and I can't find a "<" anywhere there shouldn't be one, and I went to the web address that the json is coming from: http://forecast.weather.gov/MapClick.php?lat=47.1211&lon=-88.5694&FcstType=json, and there isn't a "<" character. I used json2csharp.com to translate to C# classes, and everything there seems fine as well. Any thoughts? Here is the part of my code where I try to do all of this:

var http = new HttpClient();
var url = "http://forecast.weather.gov/MapClick.php?lat=47.1211&lon=-88.5694&FcstType=json";
var response = await http.GetAsync(url);
var result = await response.Content.ReadAsStringAsync();
var serializer = new DataContractJsonSerializer(typeof(RootObject2));
var ms = new MemoryStream(Encoding.UTF8.GetBytes(result));
var data = (RootObject2)serializer.ReadObject(ms);
return data;

Upvotes: 0

Views: 150

Answers (2)

Brian from state farm
Brian from state farm

Reputation: 2896

Your call is failing because you are not setting a header the API is expecting. Add a user agent and check for success prior to attempting to read the response.

        var http = new HttpClient();
        var url = "http://forecast.weather.gov/MapClick.php?lat=47.1211&lon=-88.5694&FcstType=json";
       //Supply the same header as chrome
        http.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36");
        var response = await http.GetAsync(url);
        if (response.IsSuccessStatusCode)
        {
            var result = await response.Content.ReadAsStringAsync();
            var ms = new MemoryStream(Encoding.UTF8.GetBytes(result));
            var serializer = new DataContractJsonSerializer(typeof(RootObject2));
            var data = (RootObject2)serializer.ReadObject(ms);
        }

Upvotes: 1

David Fawzy
David Fawzy

Reputation: 1076

check that answer, it says some issue with the connection, that he was not receiving the full response from the API

Unexpected character encountered while parsing value:

Upvotes: 0

Related Questions