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);
}
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"}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With