简体   繁体   中英

How to read a JSON file content from GitHub public repository using RestTemplate?

I need to read the content of a JSON file on a public GitHub repository using RestTemplate. The content of this JSON file keeps changing quite often, so I need to pull the data from this file once a week. I just need to get the content as String object. Is there anyway to do that?

An example of a JSON file on a public GitHub repository: JSON_File

Using RestTemplate, you can achieve it in this way.

String fortune500String = restTemplate.getForEntity
   ("https://raw.githubusercontent.com/dariusk/corpora/master/data/corporations/fortune500.json", String.class);

That will return a ResponseEntity of type String , of which you can invoke getBody() to get the String.

That's what you've asked for, but I think there's a better approach. I assume that the data itself is the only thing that changes, and not the structure. Given this assumption, create a model that represents the data, like this:

@Data
public class Fortune500 {
  private String description;
  private List<String> companies;
}

Then configure RestTemplate to be able to convert from the content type of text/plain

RestTemplate restTemplate = new RestTemplate();
MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
mappingJackson2HttpMessageConverter.setSupportedMediaTypes(List.of(MediaType.TEXT_PLAIN));
restTemplate.getMessageConverters().add(mappingJackson2HttpMessageConverter);

Then you can have RestTemplate return an instance of the model, which will be much easier for you to work with.

Fortune500 fortune500 = restTemplate.getForEntity
    ("https://raw.githubusercontent.com/dariusk/corpora/master/data/corporations/fortune500.json", Fortune500.class).getBody();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM