返回空的Json对象 [英] Returning Empty Json Object
问题描述
我试图用C#返回一个Json对象.我是MVC控制器的新手,第一次使用Json,我返回了这个对象,并且它为空.
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);
}
推荐答案
您假设框架可以推断get
和set
设置私有变量name
的值.
You are assuming that the framework can deduce that get
and set
set the private variable name
's value.. it doesn't.
相反,将name
设为公共财产,它应该起作用:
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... */
从框架的角度考虑这一点.如何确定get
或set
在做什么?他们正在访问相同的变量吗?谁知道..毕竟它的运行时间.这就是为什么无法按照您假设的方式序列化方法的原因.
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.
这篇关于返回空的Json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!