C#解析json报错Unexpected character encountered while parsing value: . Path ‘‘, line 0, position 0.
今天遇到小问题头痛了一会才解决的,总结下来吧。
具体问题是和客户做对接,解析对方二维码拿到Json字符串,JsonConvert.DeserializeObject反序列化时报错Unexpected character encountered while parsing value: . Path '', line 0, position 0.
测试数据:
[{"storename":"阿斯顿发生的看法和的","batchnum":"123456","rxtime":"2021-01-15 14:59:28","actqty":"1","storeid":"9107135","spec":"20ml*6支","payamount":"0.010000","rxid":"20210115001","owerid":"1","vemid":"1120002","dispenstime":"2021-01-15 16:18:35","prdname":"复方鲜竹沥液","cardpay":"11.000000","phcid":"02000002","prc":"0.010000","paycate":"0","usemethod":"一日一次","prdid":"11970","actamount":"0.010000","cardreim":"12.000000","phcname":"张药师","rxdtlid":"20210115001-0","usenum":"一次一支","phctime1":"2021-01-15 15:04:15","ratifier":"国药准字Z36021946","producer":"爱神的箭有限公司","reviewcontent":"通过;同意"}]
执行代码:
string strJson = System.Text.Encoding.UTF8.GetString(result);//result为测试数据
JArray jArray = (JArray)JsonConvert.DeserializeObject(strJson);//报错. Path '', line 0, position 0.位置
报错日志:
继续测试:
得出结论:发现使用UFT-8解析的结果带有BOM头,有的windows系统用记事本打开保存为UTF-8时模板带有BOM头(Byte Order Mark:字节序标记),文件读取转成byte[] 时,首部位置有固定的编码:EF BB BF。为了防止这类情况发生,需要做一个判断,去除BOM头就可以了。
正确写法:
string msg = System.Text.Encoding.UTF8.GetString(result);//result为测试数据
byte[] buffer = Encoding.UTF8.GetBytes(msg);
sResult = Encoding.UTF8.GetString(buffer, 0, buffer.Length);
byte[] bomBuffer = new byte[] { 0xef, 0xbb, 0xbf };
if (buffer[0] == bomBuffer[0]&& buffer[1] == bomBuffer[1]&& buffer[2] == bomBuffer[2])
{
int copyLength = buffer.Length - 3;
byte[] dataNew = new byte[copyLength];
Buffer.BlockCopy(buffer, 3, dataNew, 0, copyLength);
sResult = System.Text.Encoding.UTF8.GetString(dataNew);
}
JArray jArray = (JArray)JsonConvert.DeserializeObject(strJson);
foreach (var json in jArray)
{
//数据处理
string storename=json["storename"]
}
更多推荐
所有评论(0)