How to read the json below with the GSON library [duplicate]

1

How to read the json below creating the class profession with the instances of the class I would like it to be in GSON without using HashMap - KeySet() ;

{

    "profissao": {
        "jornalista": [
          "escritor",
          "legal",
          "fotografo"
       ],
       "programador": [
          "focado",
          "exatas",
          "articulado"
        ],
        "maquinista": [
          "senai",
          "mecanico",
          "visionario"
        ],
        "comediante": [
          "palhaço",
          "feliz",
          "criativo"
        ]     
      }
}
    
asked by anonymous 29.08.2017 / 16:20

2 answers

2

With answer from question Read json with the library GSON the user wants the solution to be in a strongly typed object, what is missing is to continue with this solution and then pass the data obtained for a certain type, just remembering that this % w / w of it is key and value and so your conversion is in the form of the first response.

Example:

1)

Create two classes

  

layout

import java.util.ArrayList;
import java.util.List;

public class Profissao 
{
    private String nome;
    private List<String> caracteristicas;

    public Profissao()
    {
        this.caracteristicas = new ArrayList<>();
    }
    public Profissao(String nome, List<String> caracteristicas) {
        this.nome = nome;
        this.caracteristicas = caracteristicas;
    }    
    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public List<String> getCaracteristicas() {
        return caracteristicas;
    }

    public Profissao setCaracteristicas(String caracteristicas) {
        this.caracteristicas.add(caracteristicas);
        return this;
    }    
}
  

class Profissao

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

public class Profissoes extends ArrayList<Profissao>
{
    public Profissoes(HashMap<String, HashMap<String, List<String>>> values) 
    {
        Profissao p;
        HashMap<String, List<String>> value = values.get("profissao");
        Set<String> items =  value.keySet();
        for(String item: items){
            p = new Profissao(item, value.get(item));
            this.add(p);            
        }
    }    
}

After building these two classes reuse the code as follows:

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);            
    Profissoes p = new Profissoes(c);
} 
catch (IOException e) 
{
}

where the variable class Profissoes of type p has the collection of type Profissoes that has Profissao and nome .

To retrieve values:

for(Profissao v :p)
{
     System.out.println(v.getNome());
     for(String s : v.getCaracteristicas())
     {
          System.out.print(s);
          System.out.print(" ");
     }
     System.out.println("");
}

2)

Using the classes of the example 1) make another class to deserialize this with the interface JsonDeserializer < > :

import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class ProfissoesDeserialiser implements JsonDeserializer<List<Profissao>>
{

    @Override
    public List<Profissao> deserialize(JsonElement je, 
                                       Type type,
                                       JsonDeserializationContext jdc) 
            throws JsonParseException {
        List<Profissao> ps = new ArrayList<>();
        Profissao p = null;
        Iterator<Map.Entry<String, JsonElement>> iterator = 
                                je.getAsJsonObject()
                .entrySet()
                .iterator()
                .next()
                .getValue()
                .getAsJsonObject()
                .entrySet()
                .iterator();        
        if (iterator == null) return null;
        while (iterator.hasNext())
        {
            p = new Profissao();
            Map.Entry<String, JsonElement> next = iterator.next();
            p.setNome(next.getKey());
            JsonArray carc = next.getValue().getAsJsonArray();
            for(int i = 0; i < carc.size(); i++)
            {
                p.setCaracteristicas(carc.get(i).getAsString());
            }
            ps.add(p);
        }        
        return ps;        
    }    
}

and to use ?

Gson gson = new GsonBuilder()
            .registerTypeAdapter(Profissao.class, new ProfissoesDeserialiser())
            .create();
Type profissoesTypeToken = new TypeToken<Profissao>() {}.getType();
Reader reader = new FileReader("c:\Temp\arquivo.json");
List<Profissao> fromJson = gson.fromJson(reader, profissoesTypeToken);

These two forms can be used, and the first proposal too, so now besides having 1 pattern through características has two other ways to transfer information from a key and value     

29.08.2017 / 17:46
0

Here's everything you need or more:


package utils;

import com.google.gson.Gson;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;

public class JSONUtils {

    public static String toJson(Object objeto) {
        Gson gson = new Gson();
        return gson.toJson(objeto);
    }

    public static boolean isJSONValid(String test) {
        try {
            new JSONObject(test);
        } catch (JSONException ex) {
            return false;
        }
        return true;
    }

    public static Map fromJson(String jsonString) throws Exception {
        if(jsonString == null) {
            return null;
        }
        if(!JSONUtils.isJSONValid(jsonString)) {
            throw new Exception(jsonString);
        }
        Map result = new Gson().fromJson(jsonString, Map.class);
        return result;
    }
}

Object to json:

JSONUtils.toJson(qualquerObjeto);

From JSON to object:

Map<String, Object> objeto = JSONUtils.fromJson(suaStringJson);
    
29.08.2017 / 19:23