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

时间:2022-09-15 16:18:37

I am writing a c# mechanism to upload a file to a Rails server, using Json.

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

Before getting to the file part, i am just trying to post to the server, and seem to be having some problems with the json string that is arriving at the server..

在进入文件部分之前,我只是想发布到服务器,并且似乎在到达服务器的json字符串有一些问题。

What might I be doing wrong ? I already tried two different ways of serializing the string, and even loading an already serialized string...

我可能做错了什么?我已经尝试了两种不同的序列化字符串的方法,甚至加载已经序列化的字符串......

I wonder if it has anything to do with the double quotes both at beginning and end of the string apparently being sent to server, and how to remove them from the request (without the surrounding quotes and using RestClient from WizTools.org, it all goes fine...) :

我想知道它是否与字符串的开头和结尾处的双引号有关,显然是发送到服务器,以及如何从请求中删除它们(没有周围的引号并使用来自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\"}}"')

My c# code:

我的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;


        }
    }
}

1 个解决方案

#1


5  

The problem is that the RestRequest.AddBody (source code) method actually presupposes that the content is not serialized to the correct format.

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

Meaning that it thinks that you are trying to pass the .NET string as a JSON string, instead of recognizing that you actually want to pass that string as a JSON object.

这意味着它认为您正在尝试将.NET字符串作为JSON字符串传递,而不是认识到您确实希望将该字符串作为JSON对象传递。

However, that means that you are actually doing too much work, by serializing the object to JSON yourself:

但是,这意味着您实际上做了太多工作,通过自己将对象序列化为JSON:

Replace line

request.AddBody(json_body);

with:

request.AddBody(req);

You can control the way that the serialization to JSON is done with the RestRequest.JsonSerializer property.

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

If you absolutely want to hold a JSON string, then I guess you might want to write:

如果你绝对想要持有JSON字符串,那么我想你可能想写:

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

(I see that you have a line which is commented that practically does that - why did you comment it?)

(我看到你有一条评论说实际上是这样做的 - 为什么你评论它?)

#1


5  

The problem is that the RestRequest.AddBody (source code) method actually presupposes that the content is not serialized to the correct format.

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

Meaning that it thinks that you are trying to pass the .NET string as a JSON string, instead of recognizing that you actually want to pass that string as a JSON object.

这意味着它认为您正在尝试将.NET字符串作为JSON字符串传递,而不是认识到您确实希望将该字符串作为JSON对象传递。

However, that means that you are actually doing too much work, by serializing the object to JSON yourself:

但是,这意味着您实际上做了太多工作,通过自己将对象序列化为JSON:

Replace line

request.AddBody(json_body);

with:

request.AddBody(req);

You can control the way that the serialization to JSON is done with the RestRequest.JsonSerializer property.

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

If you absolutely want to hold a JSON string, then I guess you might want to write:

如果你绝对想要持有JSON字符串,那么我想你可能想写:

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

(I see that you have a line which is commented that practically does that - why did you comment it?)

(我看到你有一条评论说实际上是这样做的 - 为什么你评论它?)