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

1

Good evening.

For the first time I'm 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, a question that came up to me is this, how can I access a key within a file?

More or less like this:

I've written an object in a single column like this:

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

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

Can I make a parser inside this file with some Gson method? Or at the time deserializar I have to have a bean with the fields and Gson takes care of it for me? Is it possible to get a getFileTmpPath () for example?

Thank you and a hug to everyone!

    
asked by anonymous 22.08.2014 / 05:46

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 only want a specific field, convert to HashMap and get the key. This approach I used does not use GSON, but it's as simple as that.

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 retrieved a shortened link through a JSON (Migre.me) API using Jackson, like this:

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 was able to retrieve the result simply using the key in question. I wrote this example in this post link

    
30.08.2014 / 01:36