JsonConvert.Serialize keeping extra backslashes? - c#

(Using Newtonsoft.Json 6.0.6)
Given this code:
var folderNames = new List<string> { #"C:\Hello", #"C:\World" };
string json = JsonConvert.SerializeObject(folderNames);
Console.WriteLine(json);
Here is what the serialized json looks like (notice there are 4 backslashes):
"[\"C:\\\\Hello",\"C:\\\\World\"]"
I get this Console output (e.g. unescaped json):
["C:\\Hello","C:\\World"]
I don't want the extra escaping backslashes to appear in the Console output. What is the recommendation?
(Code also available on .NET Fiddle: https://dotnetfiddle.net/yHJvfu)

Javascript is escaping the slash the same way c# would. \ is an escape character in javascript. The JSON is valid

Related

Deserialize Json with special character into dictionary

I got some trouble with a problem when use Newtonsoft json.net to deserialize json string to dictionary. It 's a case of my json string have some special character.
string jsonString = "{\"name\":\"Jones Smith\",\"age\":\"20\",\"description\":\"The one live with \"ALIGATOR\"\"}";
Dictionary<string, object> dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonString);
I try to find a solution in the use of json.net but i not found. So the FINAL plan is remove that "characters". So, what is the best solution for this case?
I think you can't do very much in your situation besides changing the format at the origin. The problem with your input is that there are " characters escaped the same way once in your json directly and once in your json values.
Consider the following part: "description":"The one live with "ALIGATOR""
How should a deserializer know which " should be considered part of the value or part of the json format?
I got the answer, like the last comment, that 's not valid JSON, below is valid JSON
{"name":"Jones Smith","age":"20","description":"The one live with \"ALIGATOR\""}
And all i can do is add '\' before special characters if the value of field description is "The one live with "ALIGATOR"" to make a valid JSON and convert to c# like this:
string jsonString = {\"name\":\"Jones Smith\",\"age\":\"20\",\"description\":\"The one live with \\"ALIGATOR\\"\"}

Uri.UnescapeDataString not escaping in runtime

I tried using Uri.UnescapeDataString to unescape JavaScript encoded URL. Heres the sample URL:
https://drive.google.com/open?id\u003d1n1hiV2sDFVctI8Qc9Z3EWPvEBO6KstFr\u0026usp\u003dsharing
When I tried using Uri.UnescapeDataString in C# Interactive window, it correctly unescape the URL.
Microsoft (R) Roslyn C# Compiler version 2.8.3.63029
Loading context from 'CSharpInteractive.rsp'.
Type "#help" for more information.
> Uri.UnescapeDataString("https://drive.google.com/open?
id\u003d1n1hiV2sDFVctI8Qc9Z3EWPvEBO6KstFr\u0026usp\u003dsharing)
"https://drive.google.com/open?id=1n1hiV2sDFVctI8Qc9Z3EWPvEBO6KstFr&usp=sharing"
But in real application, it just don't want to unescape. I tried from Immediate Window.
? uri
"https://drive.google.com/open?id\\u003d1n1hiV2sDFVctI8Qc9Z3EWPvEBO6KstFr\\u0026usp\\u003dsharing"
Uri.UnescapeDataString(uri)
"https://drive.google.com/open?id\\u003d1n1hiV2sDFVctI8Qc9Z3EWPvEBO6KstFr\\u0026usp\\u003dsharing"
Solution
Below code is working for me using Newtonsoft.Json JObject.
var json = "{\"su\": \"" + uri + "\"}";
var ss = JObject.Parse(json);
return ss["su"].Value<string>();
Notice the difference in these two strings:
"https://drive.google.com/open?id\\u003d1n1hiV2sDFVctI8Qc9Z3EWPvEBO6KstFr\\u0026usp\\u003dsharing"
"https://drive.google.com/open?id\u003d1n1hiV2sDFVctI8Qc9Z3EWPvEBO6KstFr\u0026usp\u003dsharing"
The first is the string you printed out in the "real" application, and the second is what you typed into the command line interpreter.
The command line interpreter, like a compiler, it what is converting \uXXXX into unicode characters, not the call to UnescapeDataString. UnescapeDataString decodes url encoded strings (like %20 characters).
Your best bet is to use Json parsing of some kind. For something simple like this, System.Web.Script.Serialization.JavaScriptSerializer is adequate.

Removing part of json string with using REGEX

My json string structure as below
...
}],"twitter":[{"id": .... blaa"}]}
...
I am trying to remove this part as below
Regex.Replace(_VarJson, string.Format("{0}.*?{1}", "\"twitter\":[{", "\"}]"), string.Empty)
But nothing removes. Where is my wrong?
Thank you in advance
In your regex pattern [{}] symbols should be escaped with \ symbol since they are reserved regex symbols ([] stands for charactrers group and {} stands for repetitions count).
So your replacement could be done as
_VarJson = Regex.Replace(_VarJson,
string.Format("{0}.*?{1}",
"\"twitter\":\\[\\{", "\"\\}\\]"),
string.Empty);
But I strongly agreed with opinion of #CommuSoft posted in comments - it's better to use some JSON library to parse your source JSON, then remove all you need from object model and write back JSON as text if needed.

Need help replacing parts of json string with regex

How can I replace the following using Regex.Replace in my c# application?
Replace all of the following:
rendition\":{
with:
rendition\":[{
So i am adding the left square bracket.
and also
Replace:
\"}}
With:
\"}]}
I am using JsonConvert from NewtonSoft to convert XML to json. The rendition element in my xmls may or may not be an array. I am trying to force the converted json to an array
Replace:
(?<=rendition:)\"\{(.*?)\"\}\}
With:
\"[{$1\"}]}
In c#:
string json2 = Regex.Replace(json, "(?<=rendition\\\\\":)\\{(.*?)\\}\\}", "[{$1}]}");
See a live demo of this C# code running on ideone.

Json.Net unexpected characters ("\") when serializing my entities

I am using the excellent Json.Net library to serialize my entities generated by entity framework. I use the following code to do so :
using (MyVoucherEntities context = new MyVoucherEntities())
{
List<MyObject> list = context.MyObjects.ToList();
string json = JsonConvert.SerializeObject(list);
}
Everything goes well I mean, the objects are correctly serialized except one think : it adds escape characters "\" that makes me having nightmare when deserializing on the client side.
[
{
\"$id\": \"1\",
\"CreationDate\": \"\\\/Date(1293186324257+0000)\\\/\",
\"ImageUrl\": \"http:\/\/www.google.com\",
\"Title\": \"Here is a title\"
} ]
Does anybody know why and how I can get rid of these escape characters slash "\" ?
I suspect it's not actually adding escape characters at all. I suspect you're just looking at the string in a debugger, and that's adding the escaping.
Try dumping it to a file or the console.
I found the reason why I had escape characters in my string ("\"). After serializing my objects, I am returning the JSON string to the client app through a WCF. Apparently, WCF is automatically adding these characters to the string before sending it to the network. It is a default behaviour and is apparently mandatory.
As I didn't want these escape characters, the workaround is to change the return type of the service to Stream and so, returning your JSON string inside a memory stream. It works perfectly and is quite fast.
It's invalid JSON because the result of serializing a list of objects is an array, i.e., the json will start with a [ and ending with a ]. To fix this, you need to wrap the list of objects in a root object (any instance of a class or an anonymous object), so, the resulting string will start with a { and end with }.
For example:
var output = new List<object>();
var json = JsonConvert.SerializeObject(new { root = output }, Formatting.Indented);
Response.Write(json);
Does this one help? I used it in my WebService to return Json content:
private HttpContent ConvertToJsonContent(object content)
{
string jsonObject = JsonConvert.SerializeObject(content, Newtonsoft.Json.Formatting.Indented);
return new StringContent(jsonObject, Encoding.UTF8, "application/json");
}
If strings have a "\" the two "\\" will come back. You can avoid this by using Unescape
private HttpContent ConvertToJsonContent(object content)
{
string jsonObject = Regex.Unescape(JsonConvert.SerializeObject(content, Newtonsoft.Json.Formatting.Indented));
return new StringContent(jsonObject, Encoding.UTF8, "application/json");
}
I should note that you have not completely quoted the outputted stuff (I got the url to work in your answer - that should have been edited into your question rather than put as an answer). The string I got back in a file was this:
"[{\"$id\":\"1\",\"CreationDate\":\"\\\/Date(1293186324257+0000)\\\/\",\"ImageUrl\":\"http:\/\/www.c-tina.com\/MyVoucherAdmin\/Images\/shop22\/burger.jpg\",\"Title\":\"Get one burger for free\",\"Description\":\"Bla lbzlfpzkfgmzke\\rdmjdgmj\\r\\r\\rlgfpzkegmkzepk\",\"ShopId\":22,\"PromotionId\":15,\"Shop\":null,\"Features\":[],\"SingleStats\":[],\"WhatsHots\":[],\"EntityKey\":{\"$id\":\"2\",\"EntitySetName\":\"Promotions\",\"EntityContainerName\":\"MyVoucherEntities\",\"EntityKeyValues\":[{\"Key\":\"PromotionId\",\"Type\":\"System.Int32\",\"Value\":\"15\"}]}}]"
the key thing to me is that there are unescaped quotes at the front and end which makes me think that whatever is outputting it is deciding it needs to be quoted and if you are surrounding it in quotes you ahve to escape the quotes that are inside it.
Without seeing the full output its hard to say if the problem is in teh code you've quoted above to generate the JSON or if there is a problem at a later step of processing this which is causing the quoting. Have you debugged and confirmed that the output of your serialize call is definitely producing the escaped version rather than it being done at a later stage potentially? If you're not used to the debugger then pay attention to Jon Skeet's suggest of dumping it to file or console to make sure there is no confusion that way.

Categories

Resources