How to read the json below with the GSON library

Asked

Viewed 2,942 times

1

How to read the json below creating the professional class through 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"
        ]     
      }
}
  • Ali the guy answered me with hashmap I would not like it to be with hash map

  • @Rodrigogabriel the guy who responded with hashMap did so because his Json is formatted in chave and valor for this one layout is the ideal shape, but, says there what format you want?

  • What the class would be like Profissao? model pass

  • Profession String nameArraylist database features

  • You want a list of a type you said correct, because it has 3 professions and its characteristics

  • and then the answer came true?

Show 1 more comment

2 answers

2


With the response of question Read json with GSON library the user wants the solution of this is in a strongly typed object, what is missing is to continue with this solution and then pass the data obtained to a certain type, only remembering that this the layout his is key and value and so its conversion is in the form of the first response.

Example:

1)

Create two classes

class Profissao

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 Profissoes

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 the construction of 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 p of the kind Profissoeshas the collection of Profissao that has nome and the características.

To recover the 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 example classes 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 also, so now in addition to having 1 standard through the layout has two other ways to transfer information from a key and value.

  • 1

    Thank you so much saved me hard now

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;
    }
}

From object to json:

JSONUtils.toJson(qualquerObjeto);

From JSON to object:

Map<String, Object> objeto = JSONUtils.fromJson(suaStringJson);

Browser other questions tagged

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