Read json with GSON library

Asked

Viewed 675 times

1

How do I read this code with the GSON library?

{
    "profissao": {
        "jornalista": [
            "escritor",
            "legal",
            "fotografo"
        ],
        "programador": [
          "focado",
          "exatas",
          "articulado"
       ],
       "maquinista": [
          "senai",
          "mecanico",
          "articulado"
      ]    
   }
}
  • You wanted to read only or pass this content to a class?

  • move to a class would be better !

1 answer

1


Using Hasmap with collection of String can work with data who has the layout of 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) 
{    
}

Exit:

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

References:

  • 1

    You can show your import?

  • @Rodrigogabriel edited, and were placed.

  • 1

    Straight guy Thank you very much!

  • There are arrows that give positive up score down negative and can also accept the answer as solution that is below the arrows a check.

  • and if I want to show separately the characteristics of each profession? type journalist n writer n legal n photographer

  • Just do a little bit of get.get(item) guy for(string ic: get.get(item)) and within that is to print the ic !

  • nice worked out I managed to do this way tbm

Show 2 more comments

Browser other questions tagged

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