简体   繁体   English

C#错误中的JSON反序列化

[英]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: 我试图在C#中反序列化一些JSON,但是当我运行程序时,却收到此错误消息:

在此处输入图片说明

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. 我已经浏览了所有代码,但在不应该存在的地方找不到“ <”,然后转到了json来自的网址: http : //forecast.weather.gov /MapClick.php?lat=47.1211&lon=-88.5694&FcstType=json ,并且没有“ <”字符。 I used json2csharp.com to translate to C# classes, and everything there seems fine as well. 我使用json2csharp.com转换为C#类,那里的一切似乎也很好。 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;

Your call is failing because you are not setting a header the API is expecting. 您的呼叫失败,因为您没有设置API期望的标头。 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);
        }

check that answer, it says some issue with the connection, that he was not receiving the full response from the API 检查该答案,表明连接存在问题,表示他没有收到API的完整回复

Unexpected character encountered while parsing value: 解析值时遇到意外字符:

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

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