c#在JSON字符串的开头和结尾添加双引号会导致服务器解码错误

本文关键字:错误 解码 服务器 添加 字符串 JSON 开头 结尾 | 更新日期: 2023-09-27 17:50:38

我正在写一个c#机制来上传一个文件到Rails服务器,使用Json。

在到达文件部分之前,我只是想发布到服务器,并且似乎与到达服务器的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;

        }
    }
}

c#在JSON字符串的开头和结尾添加双引号会导致服务器解码错误

问题是RestRequest.AddBody(源代码)方法实际上假定内容没有序列化为正确的格式。

意味着它认为你试图将。net字符串作为JSON字符串传递,而不是识别你实际上想将该字符串作为JSON对象传递。

然而,这意味着你实际上做了太多的工作,通过将对象序列化为JSON自己:

替换行

request.AddBody(json_body);

:

request.AddBody(req);

你可以用RestRequest.JsonSerializer属性控制JSON序列化的方式。

如果你绝对想保存一个JSON字符串,那么我猜你可能想写:

request.AddParameter("application/json", json_body, ParameterType.RequestBody);

(我看到你有一行被注释了,实际上就是这么做的——你为什么要注释呢?)