Bean 返回空值

Bean returning null Values

当我 运行 测试运行器 class 它应该给出预期的输出 Views=1047 而不是它 returns views =0 即空值。我做错了什么?

这是我的主要class

public class TestRunner {

public static void main(String[] args) {
    // TODO Auto-generated method stub


    JsonRestApi abc = new JsonRestApi();

    SocialBean bean = new SocialBean();

    System.out.println("Views="+bean.getViews());
}

}

这是 RestApi class 我从那里注入值到 bean

public class JsonRestApi {

public JsonRestApi() {

    try {

        String Response = "{\"Youtube Data\":\"Views\":\"1047\"}";

        JSONParser parser = new JSONParser();

        try {

            Object obj = parser.parse(Response);

            JSONObject jsonObject = (JSONObject) obj;
            JSONObject jsonObject3  = (JSONObject)jsonObject.get("Youtube Data");

            Long yviews = new Long((String)jsonObject3.get("Views"));

            SocialBean bean = new SocialBean();

            bean.setViews(yviews);

    }
  }

} }

这是我的豆子class

public class SocialBean {
private long views;
public long getViews() {
        return views;
    }
    public void setViews(long views) {
        this.views = views;
    }

SocialBean 对于 JsonRestApi 构造函数是本地的。将其设为私有字段。

private SocialBean bean = new SocialBean();
public JsonRestApi() {

try {

    String Response = "{\"Youtube Data\":\"Views\":\"1047\"}";

    JSONParser parser = new JSONParser();

    try {

        Object obj = parser.parse(Response);

        JSONObject jsonObject = (JSONObject) obj;
        JSONObject jsonObject3  = (JSONObject)jsonObject.get("Youtube Data");

        Long yviews = new Long((String)jsonObject3.get("Views"));

        bean.setViews(yviews);

 }
}

public SocialBean getSocialBean(){
   return bean;
}

在你的主要方法中:

System.out.println("Views="+abc.getSocialBean().getViews());

仅供参考:您没有在此代码中使用 Spring bean。