Skip to content

Instantly share code, notes, and snippets.

@hughpearse
Last active November 1, 2021 11:59
Show Gist options
  • Save hughpearse/6ca177ae7a884e49aed1d1d76a1cbc07 to your computer and use it in GitHub Desktop.
Save hughpearse/6ca177ae7a884e49aed1d1d76a1cbc07 to your computer and use it in GitHub Desktop.
Java http request and json processing
/**
* dependencies {
* implementation group: 'com.squareup.okhttp', name: 'okhttp', version: '2.7.5'
* implementation group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.12.3'
* }
*/
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import java.util.Iterator;
import java.util.Map;
public class Json {
public static void main(String[] args) {
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://reddit.com/r/worldnews.json")
.build();
Response response = client.newCall(request).execute();
String json = response.body().string();
JsonFactory factory = new JsonFactory();
ObjectMapper mapper = new ObjectMapper(factory);
JsonNode root = mapper.readTree(json);
Iterator<Map.Entry<String,JsonNode>> fieldsIterator = root.fields();
System.out.println(root.path("data").path("children").toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment