.NET PostSubmitter sends backslashes - c#

I'm using C# to send JSON to a PHP-Script, like this:
string json = "{";
json += "\"prop\":\"some text\"";
json += "}";
PostSubmitter post = new PostSubmitter();
post.Url = "http://localhost/synch/notein.php";
post.Type = PostSubmitter.PostTypeEnum.Post;
post.PostItems.Add("note", json);
post.Post();
Of course I'll have to escape the inner quotes, but they get sended to the script! To make things worse: There is text, which already has quotation marks, so those must be escaped to be valid JSON. In this case I want the backslashes to be transmitted. Any idea to accomplish this?

Why not serialize the custom object to json result. That way you don't have to worry about the escaping, the framework would... Here is an example using JavaScriptSerializer - Convert objects to JSON in C# using JavaScriptSerializer

Escape your backslashes \\:
json += "\\\"prop\":\\\"some text\\\"";

Ooops, thought PostSubmitter is from the .NET-framework, but it's third-party. Nevertheless: Turned out that this is a PHP-problem. If someone has a similar problem: Look for get_magic_quotes_gpc in PHP-docs.

Related

C# Pass filename as json parameter- Getting error "Unrecognized escape sequence. "

I want to pass a filepath through JSON. On deserializing I am getting error:
Unrecognized escape sequence. (43): {"Jobtype": "StepBatch","SelectedId": "D:\Input\file1.CATPart"}
I have escaped characters but it still shows error...am I missing something here?
string json = "{\"Jobtype\": \"StepBatch\",\"SelectedId\": \"D:\\Input\\file1.CATPart\"}";
var jsonObj = new JavaScriptSerializer().Deserialize<List<Arguments>>(json);
The problem is that the content of your string at execution time is:
{"Jobtype": "StepBatch","SelectedId": "D:\Input\file1.CATPart"}
That's not valid JSON, because of the backslashes in the value for SelectedId. You'd need the JSON to be:
{"Jobtype": "StepBatch","SelectedId": "D:\\Input\\file1.CATPart"}
so your C# would have to be:
string json = "{\"Jobtype\": \"StepBatch\",\"SelectedId\": \"D:\\\\Input\\\\file1.CATPart\"}";
However, given that you're immediately deserializing the JSON anyway, I'd suggest getting rid of the JSON part entirely, and just creating the Arguments values yourself.
If you need to produce JSON, create the right values directly, and then get JavaScriptSerializer (or preferrably Json.NET) to create the JSON for you, instead of hand-coding it.

Preparing a String to be used in Json

I have a string where I need to use as the body of a JSON object. I know its possible that the data could have quotes in it, so I parse through to add an escape character to those instance of quotes.. like so:
string NewComment = comment.Replace("\"", "\\\"");
However, somehow on some edgecases, a quote still makes it through. I don't know if this is something with UTF or some other issue, But I am trying to find a function that would safely create a json compatible string, I figured there has to be something like this out there, or a regex way of doing so.
Basically a TLDR is how to create a json syntax safe string from a c# string
The simple answer is don't do it this way. What if you have escaped quotes in your string? "Hello \"World\"" would become invalid with such a simple approach: "Hello \\"World\\"". JSON.Net or Newtonsoft are going to save you so many headaches in the long run.

once I serializer array i have this json format :\" before every key there is a way to ignore it?

JsonSerializer serializer = new JsonSerializer();
var query = (from item in UserDevices
select new Device
{
Device_SN= item.Device_SN,
Device_ID= item.Device_ID
}).ToList();
The response I get
"{"GetUserDevicesResult":"[{\"Device_ID\":1,\"Device_SN\":\"1504111\",\"User_Devices\":[]}"}"
Is there is a way to remove the \ and not doing manipulations of replace?
Take a look at this question:
How to remove escape characters from a JSON String
I think you have serialization issue similar to the problem described above.
Please note that JSON inherits JS notation when representing special characters and punctuations, thus the escape sequence rule also applies on .json file.
If you want to deserialize JSON data without "\" escape sequence character in C#, call JsonConvert.DeserializeObject<T>(jsonstringdata).
CMIIW.

.Net 4.0 JSON Serialization: Double quotes are changed to \"

I'm using System.Web.Script.Serialization.JavaScriptSerializer() to serialize dictionary object into JSON string. I need to send this JSON string to API sitting in the cloud. However, when we serialize it, serializer replaces all the double quotes with \"
For example -
Ideal json_string = {"k":"json", "data":"yeehaw"}
Serializer messed up json_string = {\"k\":\"json\",\"data\":\"yeehaw\" }
Any idea why it is doing so? And I also used external packages like json.net but it still doesn't fix the issues.
Code -
Dictionary<string, string> json_value = new Dictionary<string, string>();
json_value.Add("k", "json");
json_value.Add("data", "yeehaw");
var jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string json_string = jsonSerializer.Serialize(json_value);
I'm going to hazard the guess that you're looking in the IDE at a breakpoint. In which case, there is no problem here. What you are seeing is perfectly valid JSON; simply the IDE is using the escaped string notation to display it to you. The contents of the string, however, are your "ideal" string. It uses the escaped version for various reasons:
so that you can correctly see and identify non-text characters like tab, carriage-return, new-line, etc
so that strings with lots of newlines can be displayed in a horizontal-based view
so that it can be clear that it is a string, i.e. "foo with \" a quote in" (the outer-quotes tell you it is a string; if the inner quote wasn't escaped it would be confusing)
so that you can copy/paste the value into the editor or immediate-window (etc) without having to add escaping yourself
Make sure you're not double serializating the object. It happened to me some days ago.
What you're seeing is a escape character
Your JSON is a String and when you want to have " in a string you must use one of the following:
string alias = #"My alias is ""Tx3""";
or
string alias = "My alias is \"Tx3\"";
Update
Just to clarify. What I wanted say here is that your JSON is perfectly valid. You're seeing the special characters in the IDE and that is perfectly normal like Jon & Marc are pointing in their answers and comments. Problem lies somewhere else than those \ characters.

C# UTF8 encoding

I have a c# program that retrieve some JSON data and use Newtonsoft JSON to Deserialize it.
as i use persian chars in my program the JSON codes will be shown like this:\u060c \u067e\u0644\u0627\u06a9 .... also after i retrive the JSON data in my program this chars still show like its coded sample.but after i Deserialize it converted to ???? chars.
what should i do?
Your JSON deserializer is broken; \uXXXX is supposed to be turned into proper characters.
To do that yourself, use this function
// Turns every occurrence of \uXXXX into a proper character
void UnencodeJSONUnicode(string str) {
return Regex.Replace(str,
#"\\u(?<value>[0-9a-f]{4})",
match => {
string digits = match.Groups["value"].Value;
int number = int.Parse(digits, NumberStyles.HexNumber);
return char.ConvertFromUtf32(number);
});
}
(Untested code; I don't have VS available at the moment. Some exception handling would probably be nice too)
Looks like it has been JSON encoded, so you need to decode it. The DataContractJsonSerializer class can do this.
See this MSDN link for more information.

Categories