3

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);
}

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

Comments

3

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.

2 Comments

Thank you. If I don't want to make my class member public, Is there other way around ??
You can make the setter private or protected, but I think serialization requires a public getter (and deserialization would require a public setter).
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.