Okhttp and Jackson parser for downloading json data in Android
1. Include the dependencies for okhttp and jackson parser.
compile 'com.squareup.okhttp3:okhttp:3.5.0' compile 'com.squareup.okhttp3:okhttp-urlconnection:3.5.0' compile(group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: "2.8.+") compile(group: 'com.fasterxml.jackson.core', name: 'jackson-annotations', version: "2.8.+") compile(group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: "2.8.+")
2. The example activity class demonstrating the use of okhttp for downloading json data from an url and using jackson to parse it into objects.
public class MainActivity extends AppCompatActivity {
TextView tvDisplay;
FloatingActionButton fab;
Handler mHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mHandler = new Handler();
tvDisplay = (TextView) findViewById(R.id.tv_display);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
tvDisplay.setText("");
okhttpExample();
fab.setClickable(false);
}
});
}
private void okhttpExample() {
OkHttpClient client = new OkHttpClient();
HttpUrl.Builder urlBuilder = HttpUrl.parse("https://jsonplaceholder.typicode.com/posts").newBuilder();
String url = urlBuilder.build().toString();
Request request = new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
fab.setClickable(true);
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
} else {
final byte[] responseBytes = response.body().bytes();
ObjectMapper objectMapper = new ObjectMapper();
final Post[] posts = objectMapper.readValue(responseBytes, Post[].class);
//using handler to post the result back to the UI thread
mHandler.post(new Runnable() {
@Override
public void run() {
StringBuilder sb = new StringBuilder();
for(Post p : posts) {
sb.append(p.toString() + "\n\n");
}
tvDisplay.setText(sb.toString());
}
});
}
}
});
}
}
3. The Post model class with the Jackson annotations.
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Map;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Post {
@JsonProperty("userId")
private Integer userId;
@JsonProperty("id")
private Integer id;
@JsonProperty("title")
private String title;
@JsonProperty("body")
private String body;
@JsonProperty("userId")
public Integer getUserId() {
return userId;
}
@JsonProperty("userId")
public void setUserId(Integer userId) {
this.userId = userId;
}
@JsonProperty("id")
public Integer getId() {
return id;
}
@JsonProperty("id")
public void setId(Integer id) {
this.id = id;
}
@JsonProperty("title")
public String getTitle() {
return title;
}
@JsonProperty("title")
public void setTitle(String title) {
this.title = title;
}
@JsonProperty("body")
public String getBody() {
return body;
}
@JsonProperty("body")
public void setBody(String body) {
this.body = body;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("userId: " + this.userId + ", ");
sb.append("id: " + this.id + ", ");
sb.append("title: " + this.title + ", ");
sb.append("body: " + this.body);
return sb.toString();
}
}
The sample data from the server.
[
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
},
{
"userId": 1,
"id": 2,
"title": "qui est esse",
"body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
},
{
"userId": 1,
"id": 3,
"title": "ea molestias quasi exercitationem repellat qui ipsa sit aut",
"body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut"
}
]
The layout files for the Activity.
activity_main.xml
content_main.xml
Search within Codexpedia
Custom Search
Search the entire web
Custom Search
Related Posts