Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# adding double quotes to start and end of JSON string results in server decoding error

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;


        }
    }
}
like image 233
MrWater Avatar asked Jan 03 '13 14:01

MrWater


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.


1 Answers

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

like image 108
Jean Hominal Avatar answered Oct 18 '22 18:10

Jean Hominal