开发者

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

开发者 https://www.devze.com 2023-03-01 02:23 出处:网络
So for business reasons I need to force JSON.NET to escape a JSON blob like so: { url: \'http://some.uri/endpoint\' }

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 JSONCon开发者_JS百科verter subclass (e.g. MyPedanticStringConverter) and use that like so?

string json = JSONConvert.SerializeObject(
    myObject, 
    Formatting.None, 
    new MyPedanticStringConverter());


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

0

精彩评论

暂无评论...
验证码 换一张
取 消