返回空的Json对象 [英] Returning Empty Json Object

查看:471
本文介绍了返回空的Json对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用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);
}

推荐答案

您假设框架可以推断getset设置私有变量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... */

从框架的角度考虑这一点.如何确定getset在做什么?他们正在访问相同的变量吗?谁知道..毕竟它的运行时间.这就是为什么无法按照您假设的方式序列化方法的原因.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆