How to redeem a key in a Json using Gson (Google)

Asked

Viewed 470 times

1

good night.

For the first time I am manipulating a Json file with Java, because many colleagues have always told me that it is very easy to manipulate data, especially with the Google library (Gson).

Well, one question that came to me is this, how can I access a key inside a file?

Sort of like this:

I recorded an object in a single column in this way:

{  
   "fileName":"090808_072340.jpg",
   "fileSize":"337 Kb",
   "fileType":"image/jpeg",
   "fileTmpPath":"/tmp/joocebox-img/destination/manolo/090808_072340.jpg"
}

In case, I wanted to work with the key "fileTmpPath".

Can I parse inside this file with any Gson methods? Or at the time deserializar I have to have a bean with the fields and Gson takes care of it for me? Remaining only I give one getFileTmpPath() for example?

Thank you and a hug to all!

1 answer

1


You can convert to a Hashmap and search through the key. Although it is interesting to create a bean to be able to manipulate the data better, as you just want a specific field, convert it to Hashmap and take it by the key. This approach I used does not use GSON, but is as simple as.

To convert this JSON:

{ 
   "erro": 0,
   "info": "OK",
   "criado_em": "2014-08-29 20:33:47",    
   "url": "http://www.ocaminhodoprogramador.com.br",    
   "id": "llXVL",   
   "migre": "http://migre.me/llXVL",   
   "ping": "FAIL",   
   "consumo_api_hora": 0,  
   "tempo": 0.0077569485   
}

I recovered a shortened link via a JSON API (Migre.me) using Jackson, in this way:

public class App 
{
    public static void main( String[] args ) throws Exception
    {
    URI uri = new URI("http://migre.me/api.json?");
    Client client = ClientBuilder.newClient();
    WebTarget target = client.target(uri.toURL().toString()).queryParam("url", "http://www.ocaminhodoprogramador.com.br");
    String conteudo = target.request().get(String.class);
    System.out.println(conteudo);

    Map<String, String> map = new HashMap<>();
    ObjectMapper mapper = new ObjectMapper();

    map = mapper.readValue(conteudo, new TypeReference<HashMap<String, String>>() {});
    System.out.println(map.get("migre"));
    }
}

So I managed to recover the result in a simple way using the key in question. I wrote this example in this post http://www.ocaminhodoprogramador.com.br/2014/05/encurtando-links-em-java-usando-o.html

  • Hi Lucas Polo! First of all thanks for the help. That’s what I was after. I made some adaptations to my code and it worked perfectly. Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.