Json array from C# list object

Get Json array from C# List object. JSON string that we often use as object in JavaScript code, can be generated from C# code.

convert c# object to json array

Here we learn how to work with JSON object, convert C# object list to json array, JSON Serialization and De-serialization, Posting JSON string using Jquery and Picking element from JSON object and displaying on GUI

<= Click the button
JSON object in Form String

On click of above “Call JSON String Example” button, we have made a server side call using Jquery, and got the a JSON String.

Now let's look at the implementation

c# serialize object to json array

Here is the server side method written in controller

public string getBlogsJson()
            {
            string jsonString=null;
            List <blogObj> blogs = new List <blogObj>();
            blogs.Add(new blogObj() { title = "blog number 1", shortinfo = "short info 1" });
            blogs.Add(new blogObj() { title = "blog number 2", shortinfo = "short info 2" });
            blogs.Add(new blogObj() { title = "blog number 3", shortinfo = "short info 3" });
            blogs.Add(new blogObj() { title = "blog number 4", shortinfo = "short info 4" });
            blogs.Add(new blogObj() { title = "blog number 5", shortinfo = "short info 5" });
            blogs.Add(new blogObj() { title = "blog number 6", shortinfo = "short info 6" });
            jsonString = JsonConvert.SerializeObject(blogs);
            
            return jsonString;
            }

Notice, how to use SerializeObject method in c# code, method returns json string jsonString = JsonConvert.SerializeObject(blogs);.

Making JSON Call to Server
This is how my client side JavaScript call will look like

<script>
$(function () {
$("#btnJSONCall").click(function (event) {
// alert("json call");
$.ajax({
type: "POST", // or GET
                url: "@Url.Action("GetBlogList", "json")",
// data: "param1=someThing",
success: function (data) {
$("#dvJsonElement").text(data);
},
error: function () {
// something's gone wrong.
}
});
//event.preventDefault(); // stop the browser following the link
});
});
<script>

Finally just create a button with id "btnJSONCall", Done!

This is an example of getting collection object in form of JSON string in Asp.net

JavaScript Examples | JavaScript Online Course