0
I have the following code:
private class DownloadJsonAsyncTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {...}
@Override
protected Void doInBackground(Void... voids) {
p = new ControllerPosts();
arrayList = new ArrayList<>();
// Creating service handler class instance
cx = new Conexao();
String jsonStr = cx.get(url);
Log.d("Resposta: ", "> " + jsonStr);
if (jsonStr != null) {
try {
// De-serialize the JSON
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
posts = jsonObj.getJSONArray(TAG_TIPO);
// looping through All Contacts
for (int i = 0; i < posts.length(); i++) {
JSONObject c = posts.getJSONObject(i);
p.setId(Integer.parseInt(c.getString(TAG_ID)));
p.setTitulo(c.getString(TAG_TITULO));
p.setData(c.getString(TAG_DATA));
p.setConteudo(c.getString(TAG_CONTEUDO));
// p.setImagem(c.getString(TAG_IMAGEM));
// Aqui onde está gerando o erro
JSONObject img = c.getJSONObject(TAG_IMAGEM);
// JSONObject thumb = img.getJSONObject("thumbnail");
p.setImagem(c.getString(img.getString(TAG_URL_IMAGEM)));
// tmp hash map for single contact
HashMap<String, String> post= new HashMap<>();
// adding each child node to HashMap key => value
post.put(TAG_ID, String.valueOf(p.getId()));
post.put(TAG_TITULO, p.getTitulo());
post.put(TAG_DATA, p.getData());
post.put(TAG_CONTEUDO, p.getConteudo());
post.put(TAG_URL_IMAGEM, p.getImagem());
// adding post to post list
arrayList.add(post);
}
} catch (JSONException e) {
Log.e("tag", "Erro ao processar o JSON", e);
}
} else {
Log.e("Get: ", "Não foi possível obter quaisquer dados do url");
}
return null;
}
It will work properly, until I need to do an image get, it shows the message in debug:
Value http://localhost/test/image.png at thumbnail of type java.lang.String cannot be converted to Jsonobject
Someone can give me a light where I’m going wrong?
Thank you
Thank you so much for the answer, my json looks like this: "thumbnail":{"url":"http://localhost/wp-content/uploads/2016/09/bootstrap-150x150.png","width":150,"height":150}, I need to get its url, how best to do this using my parse code?
– Rubens Junior
Calling c.getJSONObject. To do this, you place the full string of your JSON as parameter (""thumbnail" ... "). I like to use the Objectmapper (with.fasterxml.Jackson.databind.Objectmapper) because when it converts you can pass an object to encapsulate everything, then it comes out ready. Then take a look, if you’re interested.
– Giuliana Bezerra
So I didn’t know Objectmapper, so I’ll give him a study, yes, thank you. In my code I am trying to do what I said: Jsonobject img = c.getJSONObject("thumbnail"); p.setImagem(img.getString("url"); Which is giving the error.. rs
– Rubens Junior
It is because you are passing "thumbnail" as parameter. You need to pass the full json string.
– Giuliana Bezerra
Got it, you’re right! Thanks for the help
– Rubens Junior