C#在JSON字符串首尾加双引号会导致服务器解码错误我正在写一个c#机制,使用Json将文件上传到Rails服务器。我只是想在到达文件部分之前发布到服务器,并且似乎在json字符串到达??服务器时遇到了一些问题。我可能做错了什么?我尝试了两种不同的序列化字符串的方法,甚至加载已经序列化的字符串......我想知道它是否与字符串开头和结尾的双引号有关,显然被发送到服务器,以及如何从请求中删除它们(不使用引号并使用WizTools.org中的RestClient,一切正常...):MultiJson::DecodeError(757:'"{"receipt"处的意外令牌:{"total":100.0,"tag_number":"xxxxx","ispaperduplicate":true},"machine":{"serial_number":"111111","safe_token":"1Y321a"}}"')我的c#代码:使用系统使用System.Collections.Generic;使用System.ComponentModel;使用系统数据;使用系统绘图;使用System.Linq;使用系统文本;使用System.Windows.Forms;使用RestSharp;使用System.Web.Script。序列化;使用Newtonsoft.Json;namespaceRonRestClient{classtemplateRequest{publicReceiptreceipt;公共类收据{公共浮动总数;公共字符串标记号;公共布尔ispaperduplicate=真;publicReceipt(floattotal,Stringtagnr){tal.total=to;this.tag_number=tagnr;}};公机机;公共类机器{公共String序列号;公共字符串安全令牌;publicMachine(Stringmachinenr,Stringsafe_token){this.serial_number=machinenr;this.safe_token=safe_token;}};}publicpartialclassForm1:Form{publicForm1(){InitializeComponent();}privatevoidbutton1_Click(objectsender,EventArgse){stringpath=@"C:file.pdf";字符串标签=“p94tt7w”;字符串machinenr="2803433";字符串safe_token="123";浮动总计=100;templateRequestreq=newtemplateRequest();req.receipt=newtemplateRequest.Receipt(total,tagnr);req.machine=newtemplateRequest.Machine(machinnr,safe_token);//字符串json_body=JsonConvert.SerializeObject(req);//stringjson_body=newJavaScriptSerializer().Serialize(req);stringjson_body=@"{""receipt"":{""total"":"+total+@",""tag_number"":"""+tagnr+@""",""ispaperduplicate"":true},""machine"":{""serial_number"":"""+machinnr+@""",""safe_token"":"""+safe_token+@"""}}";varclient=newRestClient("http://localhost:3000");varrequest=newRestRequest("/receipts",Method.POST);//设置请求主体request.AddHeader("Content-type","application/json");request.AddHeader("Accept","application/json");request.RequestFormat=DataFormat.Json;request.AddBody(json_body);//request.AddParameter("text/json",json_body,ParameterType.RequestBody);//轻松添加HTTP标头//添加要上传的文件(使用兼容动词)//request.AddFile("receipt/receipt_file",path);//执行请求IRestResponseresponse=client.Execute(request);varcontent=response.Content;//原始内容作为字符串if(response.ErrorMessage!="")content+=response.ErrorMessage;response_box.Text=content;}}}内容没有被序列化为正确的格式意味着它认为您正在尝试将.NET字符串作为JSON字符串传递,而不是认识到您真的想将字符串作为JSON对象传递。但是,这意味着您自己将对象序列化为JSON实际上做了太多工作:替换行request.AddBody(json_body);使用:request.AddBody(req);您可以使用RestRequest.JsonSerializer属性转换为JSON来控制序列化。如果你绝对想保存JSON字符串,那么我想你可能想写:request.AddParameter("application/json",json_body,ParameterType.RequestBody);(我看你有评论说其实是的-为什么要评论呢?)以上是C#学习教程:C#在JSON字符串首尾加双引号会导致服务器解码错误。分享全部内容,如果对大家有用,需要进一步了解C#学习教程,希望大家多加关注——本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
