我正在编写 ac# 机制来使用 Json 将文件上传到 Rails 服务器。
在进入文件部分之前,我只是试图发布到服务器,并且似乎对到达服务器的 json 字符串有一些问题..
我可能做错了什么?我已经尝试过两种不同的序列化字符串的方法,甚至加载已经序列化的字符串......
我想知道它是否与显然被发送到服务器的字符串开头和结尾的双引号有什么关系,以及如何从请求中删除它们(没有周围的引号并使用来自 WizTools.org 的 RestClient,一切顺利美好的...) :
MultiJson::DecodeError (757: unexpected token at '"{\"receipt\":{\"total\":100.0,\"tag_number\":\"xxxxx\",\"ispaperduplicate\":true},\"machine\":{\"serial_number\":\"111111\",\"safe_token\":\"1Y321a\"}}"')
我的 C# 代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using RestSharp;
using System.Web.Script.Serialization;
using Newtonsoft.Json;
namespace RonRestClient
{
class templateRequest
{
public Receipt receipt;
public class Receipt
{
public float total;
public String tag_number;
public bool ispaperduplicate = true;
public Receipt(float total, String tagnr)
{
this.total = total;
this.tag_number = tagnr;
}
};
public Machine machine;
public class Machine
{
public String serial_number;
public String safe_token;
public Machine(String machinenr, String safe_token)
{
this.serial_number = machinenr;
this.safe_token = safe_token;
}
};
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string path = @"C:\file.pdf";
string tagnr = "p94tt7w";
string machinenr = "2803433";
string safe_token = "123";
float total = 100;
templateRequest req = new templateRequest();
req.receipt = new templateRequest.Receipt(total, tagnr);
req.machine = new templateRequest.Machine(machinenr, safe_token);
//string json_body = JsonConvert.SerializeObject(req);
//string json_body = new JavaScriptSerializer().Serialize(req);
string json_body = @"{""receipt"" : {""total"":"+total+@", ""tag_number"":"""+tagnr+@""",""ispaperduplicate"":true},""machine"":{""serial_number"": """+machinenr+@""", ""safe_token"": """+safe_token+@"""}}";
var client = new RestClient("http://localhost:3000");
var request = new RestRequest("/receipts",Method.POST);
//set request Body
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);
// easily add HTTP Headers
// add files to upload (works with compatible verbs)
//request.AddFile("receipt/receipt_file",path);
// execute the request
IRestResponse response = client.Execute(request);
var content = response.Content; // raw content as string
if(response.ErrorMessage !="") content += response.ErrorMessage;
response_box.Text = content;
}
}
}