Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning Empty Json Object

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);
}
like image 526
PhantomM Avatar asked Jan 01 '26 08:01

PhantomM


1 Answers

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"}}

like image 126
Dustin Kingen Avatar answered Jan 03 '26 20:01

Dustin Kingen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!