Read json with the GSON library

1

How do I read this code with the GSON library?

{
    "profissao": {
        "jornalista": [
            "escritor",
            "legal",
            "fotografo"
        ],
        "programador": [
          "focado",
          "exatas",
          "articulado"
       ],
       "maquinista": [
          "senai",
          "mecanico",
          "articulado"
      ]    
   }
}
    
asked by anonymous 28.08.2017 / 15:28

1 answer

1

Using HasMap with String can work with data which has the layout of the key and value , basic example :

Code:

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

Gson gson = new Gson();

try (Reader reader = new FileReader("c:\Temp\arquivo.json"))
{
    Type listType =
           new TypeToken<HashMap<String, HashMap<String, List<String>>>>(){}.getType();
    HashMap<String, HashMap<String, List<String>>> c = gson.fromJson(reader, listType);
    HashMap<String, List<String>> get = c.get("profissao");
    Set<String> items =  get.keySet();
    for(String item: items){
        System.out.println(item);
        System.out.println(get.get(item));
        System.out.println("-----------------------");
    }    
} 
catch (IOException e) 
{    
}

Output:

run:
jornalista
[escritor, legal, fotografo]
-----------------------
maquinista
[senai, mecanico, articulado]
-----------------------
programador
[focado, exatas, articulado]
-----------------------
CONSTRUÍDO COM SUCESSO (tempo total: 0 segundos)

28.08.2017 / 16:10