Returning Empty Json Object

asp.net-mvc, c#, json

Solution

You are assuming that the framework can deduce that `get` and `set` set the private variable `name`'s value.. it doesn't.

Instead, make `name` a public property, and it should work:

public class A {
    public string Name { get; set; }
}

A obj = new A() { Name = "Abc" };
/* ...etc... */

Think about this from the framework's point of view. How can it determine what `get` or `set` are doing? Are they accessing the same variable? Who knows.. its runtime after all. This is why methods can't be serialized the way you're assuming.

Problem

I am trying to return a Json object in C#. I am new to MVC controller and using Json first time, I return this object, and its empty. ``` public class A { private string name; public void set(string data) { name = data; } public string get() { return name; } } public JsonResult Hello() { A obj = new A(); obj.set("Abc"); JavaScriptSerializer js = new JavaScriptSerializer(); string jsonVar = js.Serialize(obj); return Json(jsonVar, JsonRequestBehavior.AllowGet); } ```

Original source