Skip to main content
Home  › ... Razor

JSON Tutorials

Tutorial HomeJSON
The samples can differ based on your Razor base class or if you're running an old version.
Switch to Typed (2sxc 16+) Selected: Dynamic (Razor14 or below)
Requirements

Working with JSON Data

JSON data can be tricky. The easiest way is to convert it to a dynamic object using AsDynamic(string). Then you can easily use it in your code.

⬇️ Result | Source ➡️

  • Title: This is a JSON title
  • IsCool: True
  • Sub-item title: sub-item title
  • Is this a list/array?
  • Are the tags a list?
@inherits Custom.Hybrid.Razor14

@{
  var someJson = System.IO.File.ReadAllText(App.PhysicalPath + "/tutorials/json-use/demo.json");
  var thing = AsDynamic(someJson);
}
<ul>
  <li>Title:
    @thing.Title
  </li>
  <li>IsCool:
    @thing.IsCool
  </li>
  <li>Sub-item title:
    @thing.SubItem.Title
  </li>
  <li>Is this a list/array?
    @thing.IsList 
  </li>
  <li>Are the tags a list?
    @thing.Tags.IsList 
  </li>
</ul>

Source Code of demo.json

{
    "title": "This is a JSON title",
    "isCool": true,
    "subItem": {
        "title": "sub-item title"
    },
    "tags": [
        "some tag",
        "another tag",
        "a third tag"
    ]
}

⬇️ Result | Source ➡️

  1. some tag
  2. another tag
  3. a third tag
@inherits Custom.Hybrid.Razor14

@{
  var someJson = System.IO.File.ReadAllText(App.PhysicalPath + "/tutorials/json-use/demo.json");
  var thing = AsDynamic(someJson);
}
<ol>
  @foreach (var tag in thing.Tags) {
    <li>@tag</li>
  }
</ol>

Source Code of demo.json

{
    "title": "This is a JSON title",
    "isCool": true,
    "subItem": {
        "title": "sub-item title"
    },
    "tags": [
        "some tag",
        "another tag",
        "a third tag"
    ]
}

⬇️ Result | Source ➡️

Error Showing Content - please login as admin for details.