Bean返回null值

时间:2016-09-28 10:08:58

标签: java javabeans

当我运行Test Runner类时,它应该给出预期的输出为Views = 1047而不是它返回views = 0,即null值。我做错了什么?

这是我的主要课程

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类,我将值注入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);

    }
  }

} }

这是我的bean类

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

1 个答案:

答案 0 :(得分:1)

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。