Background
A few days back, I got a requirement to form a nested JSON object which will update the data in the HTML element through AJAX.
Working online, I could find many articles related to simple JSON format, whereas it was very hard for me to find an article which shows the simple example of nested JSON objects.
So, I thought of writing this small article and sharing the same with others.
Official definition of JSON
- JSON (JavaScript Object Notation) is a lightweight data-interchange format.
- It is easy for humans to read and write.
- It is easy for machines to parse and generate.
JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.
JsonResult Type in MVC
JsonResult is one of the important and frequently used ActionResult Types in MVC. It has been mainly used for sending data in a JSON format from the Controller.
Simple Nested Json Format
- Var testjson = new {
- Student = new {
- name: “sathish”,
- hobby: ”cricket”
- },
- Employee = new {
- name: ”ganesh”,
- hobby: ”carrom”
- }
- Employer = new {
- name: ”suresh”,
- hobby: ”football”
- }
- };
In Controller
Use this overload of JSON Method (Object, JsonRequestBehavior)
It will create a JsonResult object that serializes the specified object to JavaScript Object Notation (JSON) format using the specified JSON request behavior.
- public class HomeController: Controller {
- public JsonResult test() {
- Object testjson = new {
- Student = new {
- name: “sathish”,
- hobby: ”cricket”
- },
- Employee = new {
- name: ”ganesh”,
- hobby: ”carrom”
- },
- Employer = new {
- name: ”suresh”,
- hobby: ”football”
- }
- };
- return Json(testjson, JsonRequestBehavior.AllowGet);
- }
- }
In client side
Call the Controller action method and for simple test purposes, get the value from the JSON and show it in the JavaScript alert like the below code.
- $.ajax({
- url: "../Home /test”,
- type: "get",
- dataType: "json",
- contentType: 'application/json; charset=utf-8',
- success: function(data) {
- alert(data.student.name)
- alert(data.Employee.name)
- alert(data.Employer.name)
- }
- error: function() {
- alert("in error function");
- }
- });
You can also find this or other related articles here.
Conclusion
I hope the above information was helpful. Let me know your thoughts and feedback.