Returning Empty Json Object
Solution 1
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.
Solution 2
In C# we have properties which (in C# 3+) can be automatically created.
public class A
{
public string Name { get; set; }
}
Secondly you will need to return your object wrapped in a new object in order for the JSON to return correctly. You do not need to serialize the object yourself (since you could just return it as an ActionResult
otherwise).
public JsonResult Hello()
{
A obj = new A();
obj.Name = "Abc";
return Json(new { obj }, JsonRequestBehavior.AllowGet);
}
This will create a new Json object {"obj":{"Name":"Abc"}}
Solution 3
You shouldn'd be naming methods Get
and Set
- not even GetName
and SetName
, because if I remember my C# readings right, the CLR does that by convention when "translating" properties into CIL code (the getter becomes a "get" method and the setter becomes a "set" method). The "right" way is to use properties with meaningful names - you'll thank yourself later:
private string _name;
public string Name { get { return _name; } set { _name=value; } }
PhantomM
Updated on June 07, 2022Comments
-
PhantomM almost 2 years
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); }