JSON.Net Adding Backslash While Returning JSON Serialized String

Json.NET adding backslash while returning json serialized string

No. it doesn't

class Program
{
class Book
{
public int ID;
public string BookName;
}

static void Main()
{
var books = new List<Book> { new Book { ID = 1, BookName = "A" }, new Book { ID = 2, BookName = "B" } };

var x = from d in books
select new
{
ID = d.ID,
BookName = d.BookName
};

string str = JsonConvert.SerializeObject(x.ToList());
Console.WriteLine(str);
}
}

There could be two problems:

A) You are looking at the result from the debugger. To check for this, Put the JsonConvert in a temporary variable (like I did) and look at it with the debugger. Click on the arrow right of the hourglass and select Text Visualizer.

or

B) The calling method is transforming the object again to Json, so escaping everything.

Return Json, but it includes backward slashes \, which I don't want

i found the solution here it is

return new HttpResponseMessage() 
{
Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json")
};

Newtonsoft.Json SerializeObject without escape backslashes

What you see in debugger when looking at the json value is the string value that you should use in a C# file to obtain the same value.

Indeed you could replace

dynamic foo = new ExpandoObject();
foo.Bar = "something";
string json = Newtonsoft.Json.JsonConvert.SerializeObject(foo);

with

string json = "{\"Bar\":\"something\"}";

without changing the program's behaviour.

Thus, to obtain a different value, you should change how JsonConvert works, but JsonConvert conforms to the JSON standard, thus forget it!

If you are not actually serializing ExpandoObject (nor any other sealed class out of your control), you can use the DebuggerDisplayAttribute on the types that you are serializing in json, to define how the object will be shown during debug (in your code, the foo instance).

But a string is a string and VisualStudio is right: double-quotes must be escaped.

C# format JSON with backslash '\' in value

The basic problem is that, in a JSON string literal, the escaped solidus "\/" means exactly the same as the unescaped solidus "/", and Json.NET parses and interprets this escaping at a very low level, namely JsonTextReader.ReadStringIntoBuffer(). Thus there's no way for higher level code to detect and remember whether a string literal was formatted as "\/Date(2015-02-02)\/" or "/Date(2015-02-02)/" and later write back one or the other as appropriate.

If you are OK with always adding the extra escaping to strings that start with /Date( and end with )/, you can use a custom subclass of JsonTextWriter to do this:

public class DateLiteralJsonTextWriter : JsonTextWriter
{
public DateLiteralJsonTextWriter(TextWriter writer) : base(writer) { }

public override void WriteValue(string value)
{
const string startToken = @"/Date(";
const string replacementStartToken = @"\/Date(";
const string endToken = @")/";
const string replacementEndToken = @")\/";

if (value != null && value.StartsWith(startToken) && value.EndsWith(endToken))
{
var sb = new StringBuilder();

// Add the initial quote.
sb.Append(QuoteChar);

// Add the new start token.
sb.Append(replacementStartToken);

// Add any necessary escaping to the innards of the "/Date(.*)/" string.
using (var writer = new StringWriter(sb))
using (var jsonWriter = new JsonTextWriter(writer) { StringEscapeHandling = this.StringEscapeHandling, Culture = this.Culture, QuoteChar = '\"' })
{
var content = value.Substring(startToken.Length, value.Length - startToken.Length - endToken.Length);
jsonWriter.WriteValue(content);
}

// Strip the embedded quotes from the above.
sb.Remove(replacementStartToken.Length + 1, 1);
sb.Remove(sb.Length - 1, 1);

// Add the replacement end token and final quote.
sb.Append(replacementEndToken);
sb.Append(QuoteChar);

// Write without any further escaping.
WriteRawValue(sb.ToString());
}
else
{
base.WriteValue(value);
}
}
}

Then parse with DateParseHandling = DateParseHandling.None as you are currently doing:

var settings = new JsonSerializerSettings { DateParseHandling = DateParseHandling.None };

var sb = new StringBuilder();
using (var writer = new StringWriter(sb))
using (var jsonWriter = new DateLiteralJsonTextWriter(writer) { Formatting = Formatting.Indented})
{
JsonSerializer.CreateDefault(settings).Serialize(jsonWriter, JsonConvert.DeserializeObject(extract, settings));
}

Console.WriteLine(sb);

This prints:

{
"key": "\/Date(2015-02-02)\/"
}

asp.net json serializer adding backslash \ to my properties

That should be correct. When sending JSON back to the browser, all property names must be in quotes. The backslashes you see are Visual Studio escaping the strings when viewing them (I hope, you didn't mention when you're seeing this).

If you actually send that data back out on the wire it should come across as

{"int1": 31, "int2":5436}

which is proper JSON notation.

See Wikipedia for an example of JSON notation.

Why does C# add extra backslashes to my data?

I think you can try this method

 var raw = new WebClient().DownloadString("http://ip-api.com/json");

var json = JToken.Parse(raw.ToString());

string Latitude = (string)json[@"lat"];
string Longitude = (string)json[@"lon"];

How to serialize JSON to string without escape characters in .NET Core?

The escape characters aren't there. If we can reasonably assume that your sensorData is something like:

class SensorData
{
public int Id { get; set; }
public DateTime TimeStamp { get; set; }
public double Value { get; set; }
}

then if I do:

var sensorData = new SensorData {
Id = 100201,
TimeStamp = DateTime.Now,
Value = 12.3,
};
string s = JsonConvert.SerializeObject(sensorData);
Console.WriteLine(s);

the output is:

{"Id":100201,"TimeStamp":"2018-02-08T10:30:40.2290218+00:00","Value":12.3}

The escape characters are an IDE feature, not part of the JSON. The IDE shows you strings as you would need to copy and paste them in your target language; so: if the value is the JSON posted above, then the IDE will show it as a C# literal:

"{\"Id\":100201, ...snip... , \"Value\":12.3}"

But: that isn't the contents of the string.

C# Doesn't Remove Backslashes While Writing JSON Data Into File

As has been noted in comments, the problem is that you're converting an object into a JSON string here:

string propertyStr = JsonConvert.SerializeObject(propertiesArray);

And then you're setting that string (which includes double quotes etc) as a JSON property here:

result["properties"] = propertyStr;

I believe you don't want it as a string property, but just as the object. So instead, you want the value of the property to be the JToken itself. So I'd expect this to work:

result["properties"] = JToken.FromObject(propertiesArray);


Related Topics



Leave a reply



Submit