green
green

Reputation: 393

How to properly parse json objects to array with Jackson?

I would like to ask how to properly convert the next json string. I have this string:

{"response":{"meta":{"hits":1326,"time":55,"offset":0},"docs":[{"web_url":"http://www.nytimes.com/2016/04/05/fashion/china-luxury-goods-retail.html"},{"web_url":"http://www.nytimes.com/2016/04/05/fashion/luxury-goods-retail.html"},...

and I would like only the "docs" array. I am using Jackson Converter in this way:

    RestTemplate restTemplate=new RestTemplate();
    MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
    jsonConverter.setSupportedMediaTypes(Arrays.asList(new MediaType("text", "json", MappingJackson2HttpMessageConverter.DEFAULT_CHARSET)));
    restTemplate.getMessageConverters().add(jsonConverter);
    ArrayList<WebUrl> topStories=restTemplate.getForObject(URL,Docs.class).getUrls();

and here is my Docs class:

@JsonIgnoreProperties(ignoreUnknown = true)

public class Docs {
  @JsonProperty("docs")
  private ArrayList<WebUrl> urls;

  public Docs(ArrayList<WebUrl> urls) {
     this.urls= urls;
  }

  public Docs(){

  }

  public ArrayList<WebUrl> getUrls() {
    return urls;
  }

  public void setUrls(ArrayList<WebUrl> urls) {
    this.urls=urls;
  }

 }

And here is my WebUrl.class

public class WebUrl {

@JsonProperty("web_url")
private String webUrl;

public WebUrl(){

}

public String getWebUrl() {
    return webUrl;
}

public void setWebUrl(String webUrl) {
    this.webUrl = webUrl;
}

public WebUrl(String webUrl) {

    this.webUrl = webUrl;
}
}

But it gives me null pointer exception on the array. How can I fix this?

Upvotes: 0

Views: 1521

Answers (1)

Deendayal Garg
Deendayal Garg

Reputation: 5158

You need to have classes Like below. as @cricket_007 mentioned you can not extract something out of middle.

Result.Java

import com.fasterxml.jackson.annotation.JsonProperty;

 public class Result {
    @JsonProperty("response")
    public Response response;
}

Response.Java

import com.fasterxml.jackson.annotation.JsonProperty;

import java.util.ArrayList;
import java.util.List;

public class Response {
    @JsonProperty("docs")
    public List<Doc> docs = new ArrayList<Doc>();
}

Doc.java

import com.fasterxml.jackson.annotation.JsonProperty;

public class Doc {
    @JsonProperty("web_url")
    public String webUrl;
}

Once you have these classes, you can call the service like below.

Result forObject = restTemplate.getForObject("yourURL", Result.class);

And then, from result you can extract the list of URLs.

Upvotes: 2

Related Questions