views:

157

answers:

2

Hi,

I was weaving my own json programatically, and was adviced to not roll my own as escaping for the forward slash and line breaks won't be enough basically.

My json is to look like:

{"rc": "200", "m" : "", "o": "<div class='s1'>
            <div class='avatar'>                    
                <a href='\/asdf'>asdf<\/a><br \/>
                <strong>0<\/strong>
            <\/div>
            <div class='sl'>
                <p>
                    444444444
                <\/p>
            <\/div>
            <div class='clear'>
            <\/div>                        
        <\/div>"}

How can I use json.net library to create this? I don't want to create an object and serialize it as at this point I don't have the data in a class/object.

+1  A: 
JavaScriptConvert.SerializeObject(new {
    rc = 200,
    m = "",
    o = @"<div class='s1'>
            <div class='avatar'>                    
                <a href='/asdf'>asdf</a><br />
                <strong>0</strong>
            </div>
            <div class='sl'>
                <p>
                    444444444
                </p>
            </div>
            <div class='clear'>
            </div>                        
        </div>"
});

Or, if you need this as a controller result and you're using ASP.NET MVC you can just use the JsonResult ActionResult

Mauricio Scheffer
+1  A: 

This will give you a object that you can continue to modify or just do a ToString on if all you want is the JSON text.

JObject o = new JObject();
o["rc"] = new JValue(200);
o["m"] = new JValue("");
o["o"] = new JValue(@"<div class='s1'>
      <div class='avatar'>             
          <a href='asdf'>asdf</a><br />
          <strong>0</strong>
      </div>
      <div class='sl'>
          <p>
              444444444
          </p>
      </div>
      <div class='clear'>
      </div>                        
  </div>");

Console.WriteLine(o.ToString());
James Newton-King
how fast is this library?
mrblah
http://james.newtonking.com/archive/2008/10/27/json-net-3-5-beta-1-big-performance-improvements-compact-framework-support-and-more.aspx
James Newton-King
if you don't get rewarded an answer to this question who will? hehe thanks!
mrblah
btw, is this the fastest way then?
mrblah