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

时间:2013-01-03 14:49:59

标签: c# json serialization

我正在编写一个c#机制,使用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;


        }
    }
}

1 个答案:

答案 0 :(得分:6)

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

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

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

替换行

request.AddBody(json_body);

使用:

request.AddBody(req);

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

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

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

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