Home > OS >  ResponseEntity is returning null when imposing class object
ResponseEntity is returning null when imposing class object

Time:11-10

I am new to Spring boot and sorry in case it's very basic but I am posting as I have tried other ways and checked similar threads as well.

If I use below code it's returning correct response

ResponseEntity<String> responseEntityString = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);

Output

[{"Id":"123aa","TenId":5198,"Name":"test","Description":"test11","Tags":[]}]

Now I have created workspace class like below (getter/setter/arg constructor and no-arg construcntor is also there)

public class Workspace {

    private String Id;
    private String TenId;
    private String Name;
    private String Description;
    private List<String> Tags;
 }

Now I execute the below code -

ResponseEntity<List<Workspace>> response = restTemplate.exchange(
                  url,
                  HttpMethod.GET,
                  requestEntity,
                  new ParameterizedTypeReference<List<Workspace>>(){});
        List<Workspace> employees = response.getBody();
        employees.stream().forEach(entry -> System.out.println(entry.getId()   ": "   entry.getName()));

It's returning

null: null

Below is returning true

System.out.println("Value "  response.hasBody());

Below is returning - New Values [com.pratik.model.Workspace@3cbf1ba4]

New Values [com.pratik.model.Workspace@3cbf1ba4]

So please advise what needs to change to get the values

================================================================ Initialized resttemplate bean like below

 public class app1 {
    static RestTemplate restTemplate = new RestTemplate();
    static String url =   url;
    public static void main(String[] args) {
        SpringApplication.run(app1.class, args);
        getCallSample();
        
    }

===============================================================

Update on the latest code

ResponseEntity<Workspace[]> responseNew = restTemplate
                  .exchange(
                    url,
                    HttpMethod.GET,
                    requestEntity,
                    Workspace[].class);
Workspace [] employees1 = responseNew.getBody();
List<Workspace> list = Arrays.asList(employees1);
list.stream().forEach(entry -> System.out.println(entry.getId()   ": "   entry.getName()));

Still the response is

null: null

=============================================================== Another update When tried with String.class it's returning

[{"Id":"abc","TenId":11,"Name":"tt1 Workspace","Description":"testtenant Workspace (System Generated)","Tags":[]}]

But when using workspace class - it's returning -

[Id=null, TenId=null, Name=null, Description=null, Tags=null, getId()=null, getTenId()=null, getName()=null, getDescription()=null, getTags()=null]

So is using Workspace[].class would be the right method ?

CodePudding user response:

Replace your static RestTemplate restTemplate = new RestTemplate(); variable for a real bean:

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

@Configuration
public class app1 {
    //remove this variable
    //static RestTemplate restTemplate = new RestTemplate();
    static String url = "your_url";
    public static void main(String[] args) {
        SpringApplication.run(app1.class, args);
        //getCallSample();
    }

    //create a proper RestTemplate bean
    @Bean
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        //add a converter so you can unmarshall the json content
        MappingJacksonHttpMessageConverter converter = new MappingJacksonHttpMessageConverter();
        //this is an example to set an ObjectMapper instance
        //you can define a bean to configure the ObjectMapper
        //with specific details like avoid unmarshalling unknown fields
        converter.setObjectMapper(new ObjectMapper());
        restTemplate.getMessageConverters().add(converter);
        return restTemplate;
    }
}

Now, in the method you're using the rest template. Get it from Spring's application context rather than using your own static bean. Example:

@Component
public class WorkspaceService {

    private final RestTemplate restTemplate;

    public WorkspaceService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public List<Workspace> getWorkspaces() {
        ResponseEntity<List<Workspace>> response = restTemplate.exchange(
              url,
              HttpMethod.GET,
              requestEntity,
              new ParameterizedTypeReference<List<Workspace>>(){});
        List<Workspace> employees = response.getBody();
        employees.stream().forEach(entry -> System.out.println(entry.getId()   ": "   entry.getName()));
        return employees;
    }
}

Now you can use this bean in your components. For example, if you want to use it in main class:

@Configuration
public class app1 {
    static String url = "your_url";
    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(app1.class, args);
        WorkspaceService ws = ctx.getBean(WorkspaceService.class);
        ws.getWorkspaces();
    }

    //create a proper bean
    @Bean
    public RestTemplate restTemplate() {
        /* code from above... */
    }
}

CodePudding user response:

The issue is resolved by changing the Pojo class (used this to get the class https://json2csharp.com/code-converters/json-to-pojo) to

public class Root{
    @JsonProperty("Id") 
    public String id;
    @JsonProperty("TenantId") 
    public int tenantId;
    @JsonProperty("Name") 
    public String name;
    @JsonProperty("Description") 
    public String description;
    @JsonProperty("Tags") 
    public ArrayList<Object> tags;
}

and the code is used

ResponseEntity<Workspace[]> responseNew = restTemplate
                  .exchange(
                    url,
                    HttpMethod.GET,
                    requestEntity,
                    Workspace[].class);
                Workspace [] employees1 = responseNew.getBody();
list.stream().forEach(entry -> System.out.println(entry.getDescription() ": "   entry.getId()   ": "   entry.getName()));

Thanks for the responses , got to learn a lot from the answers

  • Related