You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Newtonsoft.Json解析HttpWebRequest响应至myDATA类时出现解析错误

Newtonsoft.Json解析HttpWebRequest响应至myDATA类时出现解析错误

看起来你在把HTTP响应解析到自定义类的时候遇到了麻烦,我帮你梳理一下常见问题点,再给出完整的修正代码~

可能导致错误的几个原因

  • 你目前的代码只处理了请求发送环节,没有完整读取服务器的响应内容,这是最常见的遗漏点
  • 直接解析前未确认服务器返回的是有效JSON(比如服务器可能返回错误页面、非JSON格式的提示文本)
  • 使用ASCII编码可能导致特殊字符/非英文内容乱码,进而影响JSON解析

完整的修正代码

首先保留你的myDATA类(顺便提一句:按C#编码规范,类名建议改成MyData,属性名用Data1/Data2,不过只要和JsonProperty标签对应就不影响解析):

public class myDATA
{
    [JsonProperty("data1")]
    public string data1 { get; set; }
    [JsonProperty("data2")]
    public string data2 { get; set; }
}

然后补充完整的请求发送、响应读取和解析逻辑:

string url = "https://www.domain/test.php";
HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create(url);

// 替换成UTF-8编码,避免ASCII的局限性
Encoding encoding = Encoding.UTF8;
string postData = $"key={HttpUtility.UrlEncode(txtLISANS.Text)}&hwid={HttpUtility.UrlEncode(Genel.HWID().ToString())}";
byte[] byteArray = encoding.GetBytes(postData);

httpWReq.Method = "POST";
httpWReq.ContentType = "application/x-www-form-urlencoded";
httpWReq.ContentLength = byteArray.Length;
httpWReq.Accept = "application/json";

// 发送POST请求
using (Stream stream = httpWReq.GetRequestStream())
{
    stream.Write(byteArray, 0, byteArray.Length);
}

try
{
    // 获取并读取响应
    using (HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse())
    using (Stream responseStream = response.GetResponseStream())
    using (StreamReader reader = new StreamReader(responseStream, encoding))
    {
        // 读取完整的响应文本
        string jsonResponse = reader.ReadToEnd();
        
        // 先打印响应内容,方便排查是否是有效JSON
        Console.WriteLine("服务器返回内容:" + jsonResponse);
        
        // 解析到myDATA类
        myDATA result = JsonConvert.DeserializeObject<myDATA>(jsonResponse);
        
        // 验证解析结果
        if (result != null)
        {
            Console.WriteLine("解析成功:data1=" + result.data1 + ",data2=" + result.data2);
        }
    }
}
catch (WebException ex)
{
    // 处理HTTP请求错误(比如404、500状态码)
    if (ex.Response is HttpWebResponse errorResponse)
    {
        using (StreamReader reader = new StreamReader(errorResponse.GetResponseStream()))
        {
            string errorContent = reader.ReadToEnd();
            Console.WriteLine("请求失败,服务器返回错误:" + errorContent);
        }
    }
    else
    {
        Console.WriteLine("请求异常:" + ex.Message);
    }
}
catch (JsonException ex)
{
    // 专门捕获JSON解析错误,快速定位问题
    Console.WriteLine("JSON解析失败:" + ex.Message);
}

额外注意事项

  1. 一定要捕获异常:分别处理HTTP请求异常和JSON解析异常,能帮你快速定位是请求出错还是格式不匹配
  2. 先打印响应内容:如果解析失败,先看服务器返回的是不是你预期的JSON结构,有时候服务器会返回错误提示文本而非JSON
  3. 编码统一:全程用UTF-8编码,避免因字符乱码导致的解析失败

备注:内容来源于stack exchange,提问作者Noucoder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.16 12:28:15