Parse REST json to String in Java Spring - Why So Difficult?
I’ve been working on a java Spring project after a year of building in python. Recently I needed a single string (NPI Number) from the US Health and Human Services api. It's a simple api with no auth.
In python it's easy:
request_url = f”https://npiregistry.cms.hhs.gov/api/?version=2.1&first_name={name_parts[0]}&middle_name={name_parts[1]}&last_name={name_parts[2]}&state=nj”
npi_resp = requests.get(request_url) json = npi_resp.json() npi = json[“results”][0][“number”]
However in java spring it was anything but simple. The Spring Documentation does not show how to “grab one string” and parse it easily. I guess they consider it bad manners in their relentless pursuit of design perfection. They only how to use the built-in Jackson library to serialize GET results into POJO (Plain Old Java objects).
That solution is often overkill. Sometimes you just want a String. To accomplish this I had to dig around quite a bit through old Stackoverflow articles (proving stackoverflow is still very useful as an archive of human-tested tips).
Here it is.
//In pom.xml, include the json dependency at https://mvnrepository.com/artifact/org.json/json
//put together a url as in the python example above. I'm not your mom.
String result = restClient.get()
.uri(sb.toString())
.header("Content-Type", "application/json")
.retrieve()
.body(String.class);
JSONObject json = new JSONObject(result);
JSONArray jsonArray = json.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonElem = jsonArray.getJSONObject(i);
log.info("npi json obj: {}", jsonElem);
String npi = jsonElem.getString("number");
npis.add(npi);
log.info("npi number: {} for: {}", npi, fullName);
}
I hope this helps someone.