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

RestSharp获取Windows-1252编码CSV时瑞典字符丢失问题求助

解决RestSharp获取Windows-1252编码CSV时的字符乱码问题

问题核心

你直接读取response.Content时,RestSharp默认采用UTF-8解码,但API返回的是Windows-1252编码,导致瑞典语特殊字符(如å、ä、ö)丢失或乱码。

简便解决方案

不要直接使用response.Content,而是从响应的原始字节流手动用Windows-1252编码解码。修改后的代码如下:

var jsonFile = JsonConvert.DeserializeObject(File.ReadAllText("C:\\Users\\svant\\source\\repos\\testSCB3Api\\testSCB3\\Data\\Json\\question.json"));

using (var client = new RestClient("https://api.scb.se/OV0104/v1/doris/sv/ssd/START/BE/BE0101/BE0101H/FoddaK"))
{
    BornModel bornModel = new BornModel();

    var payload = jsonFile;
    var request = new RestRequest();
    request.AddStringBody(payload.ToString(), DataFormat.Json);
    // 获取完整响应对象,而非直接读取Content
    var response = client.PostAsync(request).Result;
    
    // 用Windows-1252编码解码原始字节数组
    var csvContent = Encoding.GetEncoding(1252).GetString(response.RawBytes);
            
    using (var stringReader = new StringReader(csvContent))
    {
        using (var csvReader = new CsvReader(stringReader, CultureInfo.InvariantCulture))
        {
            csvReader.Context.RegisterClassMap<BornModelMap>();
            var records = csvReader.GetRecords<BornModel>();

            foreach (var record in records)
            {
                record.region = bornModel.region;
                record.kön = bornModel.kön;
                record.Levandefödda2016 = bornModel.Levandefödda2016;
                record.Levandefödda2017 = bornModel.Levandefödda2017;
                record.Levandefödda2018 = bornModel.Levandefödda2018;
                record.Levandefödda2019 = bornModel.Levandefödda2019;
                record.Levandefödda2020 = bornModel.Levandefödda2020;
            }
        }
    }
}

关键修改点

  • 放弃直接读取response.Content,改用response.RawBytes获取响应原始字节数组
  • 通过Encoding.GetEncoding(1252)将字节数组解码为字符串,确保瑞典语特殊字符正确解析
  • 后续CSV读取逻辑无需调整

补充说明

如果API响应头明确标注了编码(如Content-Type: text/csv; charset=windows-1252),也可以通过response.ContentEncoding获取编码名称,但直接指定1252编码更可靠,能避免响应头缺失或识别错误的情况。

内容的提问来源于stack exchange,提问作者Svante Pålsson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 09:10:32