Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is very much the way that you would go about generating XML, but JSON is a little different. If you have updated your Umbraco to one of the later editions, then you use Razor to render JSON in this sort of way:</p> <pre> @{ var builder = new System.Text.StringBuilder(); foreach (var car in cars) { builder.Append("{"); builder.Append(Json.Encode("reg") + ":" + Json.Encode(car.Registration) + ","); builder.Append(Json.Encode("model") + ":" + car.Model); // INSERT OTHER VALUES HERE builder.Append("}"); if (car.Registration != cars.Last().Registration) { builder.Append(","); } count++; } } @Html.Raw(builder.ToString()) </pre> <p>Another more interesting way is JSON.NET - a good option if you are using custom objects in your application. You populate your objects, and then pass them through JSON.NET. <a href="http://james.newtonking.com/projects/json-net.aspx" rel="nofollow">See here for more details</a>.</p> <pre> Product product = new Product(); product.Name = "Apple"; product.Expiry = new DateTime(2008, 12, 28); product.Price = 3.99M; product.Sizes = new string[] { "Small", "Medium", "Large" }; string json = JsonConvert.SerializeObject(product); //{ // "Name": "Apple", // "Expiry": "2008-12-28T00:00:00", // "Price": 3.99, // "Sizes": [ // "Small", // "Medium", // "Large" // ] //} Product deserializedProduct = JsonConvert.DeserializeObject(json); </pre> <p>The beauty of this library is that you can also create strings and convert them to JSON. The only caveat is that you have to watch your JavaScript when trying to read the JSON. Things like single (') and double (") quotes can break your code.</p> <pre> string json = @"{ ""Name"": ""Apple"", ""Expiry"": "2008-12-28T00:00:00", ""Price"": 3.99, ""Sizes"": [ ""Small"", ""Medium"", ""Large"" ] }"; JObject o = JObject.Parse(json); string name = (string)o["Name"]; // Apple JArray sizes = (JArray)o["Sizes"]; string smallest = (string)sizes[0]; // Small </pre> <p>Your code could work if you used the System.Xml namespace (XmlDocument, XmlAttributes, XmlNode). It is unclear as to which Node object you are using but I will assume it is Umbraco's Node (I would work with a new DynamicNode() instead btw) and in which case you cannot just create them like that with populated properties. You have to create one in the Umbraco database before reading its values.</p> <p>Hopefully this should give you something to go on with. <em>Happy coding</em>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload