Reputation: 1518
When I run the Test Runner class it should give the expected output as Views=1047 instead it returns views =0 i.e null value. What am I doing wrong?
This is my main 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());
}
}
This is RestApi class from where i am inject the values to 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);
}
}
} }
This is my bean class
public class SocialBean {
private long views;
public long getViews() {
return views;
}
public void setViews(long views) {
this.views = views;
}
Upvotes: 1
Views: 484
Reputation: 3791
SocialBean is local to JsonRestApi constructor. Makes it as private field.
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;
}
In your main method :
System.out.println("Views="+abc.getSocialBean().getViews());
FYI : you are not using Spring bean in this code.
Upvotes: 1