11

Say I have a class like

public class MyTestClass
{
    public MyTestClass()
    {
        Testing = "check ' out";
    }
    public string Testing { get; set; }
}

And JavascriptSerializer/JsonNet serializers like :

public IHtmlString ToJsonNet(object value)
{
    return new MvcHtmlString(JsonConvert.SerializeObject(value));
}

public IHtmlString ToJson(object value)
{
    var json = new JavaScriptSerializer();
    return new MvcHtmlString(json.Serialize(value));
}

Then in a view I have

 @(Serializers.ToJsonNet(new MyTestClass()))
 @(Serializers.ToJson(new MyTestClass()))

The JsonNet will return {"Testing":"check ' out"}, while the JavascriptSerializer will return {"Testing":"check \u0027 out"}. I wish to create a javascript object like

var model = $.parseJSON('@jsonString');

But this only works if the apostrophe is encoded. Otherwise, the apostrophe makes my javacript look like

var model = $.parseJSON('{"Testing":"check ' out"}');

which fails because the inserted apostrophe makes parseJSON escape my string too early.

JavascriptSerializer encodes the apostrophe as \u0027 by default while JSON.NET (which I want to use) does not. How can I change JSON.NET to do this? Is there a setting I'm missing? Is there a different way I can parse my JSON string into javascript where the apostrophe is OK?

user1399487
  • 111
  • 1
  • 4

3 Answers3

1

The following answer indicates that the two should be equivalent. https://stackoverflow.com/a/5022386/1388165

If it is the parseJSON call failing, perhaps double quotes instead of single quotes in the argument would help.

Community
  • 1
  • 1
Andrew N Carr
  • 336
  • 1
  • 5
  • Because the jsonstring contains both double quotes and single quotes, using either of them in the parseJson currently causes a failure because it escapes the jsonString early. – user1399487 May 16 '12 at 19:57
1

Have you tried escaping the apostrophe with a "\"?

Something like Testing = "check \' out";


You should also take a look at this post, there seem to be some interesting answers for you here.

Community
  • 1
  • 1
Padrus
  • 2,013
  • 1
  • 24
  • 37
1

Try this:

{"Testing":"check \u0027 out"}
Entaah Laah
  • 131
  • 2
  • 4
  • When I paste text into an html text area from Microsoft Word and then use that value to serialize it in C#, the apostrophe does not get serialized as \u0027 but instead it remains as "'" character. Any thoughts? – nav Jan 15 '15 at 15:14