Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way to force JSON.Net to escape forward slash (solidus) characters?

So for business reasons I need to force JSON.NET to escape a JSON blob like so:

{ url: 'http://some.uri/endpoint' }

As

{ "url": "http:\/\/some.uri\/endpoint" }

Which is to say it needs to escape the forward-slash solidus characters. I know the JSON spec doesn't require this, and than technically the two are equal, but in this particular situation I need to create the exact same string with JSON.NET as I'm getting from somewhere else.

What's the best way to coerce JSON.NET to do this?

Would it make sense to create a new JSONConverter subclass (e.g. MyPedanticStringConverter) and use that like so?

string json = JSONConvert.SerializeObject(
    myObject, 
    Formatting.None, 
    new MyPedanticStringConverter());
like image 884
Ryan Avatar asked Apr 26 '11 23:04

Ryan


People also ask

Why are there slashes in JSON?

Those backslashes are escape characters. They are escaping the special characters inside of the string associated with JSON response. You have to use JSON. parse to parse that JSON string into a JSON object.


1 Answers

If you're looking for a generic solution, writing a converter is perhaps the way to go.

Another solution, would be adding a property to the class in the following manner:

[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public class MyObject
{
    public string Url
    {
        get;
        set;
    }

    [JsonProperty("url")]
    private string UrlJson
    {
        get { return this.Url.Replace("/", "\\/"); }
    }
}

(You can obviously change the Replace method to something more sophisticated and more thorough).

like image 142
Mikey S. Avatar answered Nov 24 '22 12:11

Mikey S.