6

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

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..

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...) :

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:

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;


        }
    }
}
Jesse Wolgamott
  • 40,197
  • 4
  • 83
  • 109
MrWater
  • 1,797
  • 4
  • 20
  • 47

1 Answers1

7

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

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.

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

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.

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

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?)

Jean Hominal
  • 16,518
  • 5
  • 56
  • 90
  • Awesome, not only you helped me solving this, as you managed to suggest two different solutions for my problem. I had it commented because it wasn't working : I was using `text/json` instead of `application/json`. Anyway, using `request.AddBody(req)` does the trick too...Now i just have to figure out how to add the file to within the receipt structure. Thanks ! – MrWater Jan 03 '13 at 15:19
  • If `request.AddBody(req)` works, I strongly suggest that you use that, because it is clearly the way that you are supposed to use RestSharp. – Jean Hominal Jan 03 '13 at 15:31
  • Excellent! I had the exact same problem - googled it, first result is this, boom! :) Thanks! – albogdano Sep 08 '15 at 11:52