How to take received data in JSON and store in a class

Asked

Viewed 1,289 times

0

Good afternoon!

I am having difficulty implementing code to rescue the data that is coming in JSON and store this data in a class.

If anyone can help me, I’d appreciate it.

My idea is to receive the data from the webservice and store this data from Json in the user class, as I will use this data to write to the application database.

Follow the excerpt of my code below

//Cria e inicializa um objeto Gson
Gson gsonUsuario = new Gson();

//Passa os dados que estão nas variaveis para o parametro
Transmissao_Env transmissao_env = new Transmissao_Env();
transmissao_env.setEmail(email);
transmissao_env.setSenha(senha);
transmissao_env.setFuncao(funcao);

//Realiza conexão com o servidor webservice e passa os parametros junto
String resultado = ToolBox.comunicacao("http://www.meusite.com.br/ws/index.php", gsonUsuario.toJson(transmissao_env));

//Pega o valor antes da tag WSTAG que foi recebida do webservice
String parRes[] = resultado.split("#WSTAG#");

//Verifica a quantidade de caracteres
switch (parRes.length) {
    case 2:

        //Verifica se o resultado do webservice foi gerado corretamente(0)
        if (parRes[0].equals("0")) {
            //Realiza a conversão do Json para um objeto do tipo
            Usuario mUsuario = gsonUsuario.fromJson(parRes[1], Usuario.class);

            //Neste ponto que preciso de ajuda
            mUsuarioDao = new UsuarioDao(mContext);
            mUsuarioDao.insereUsuario(mUsuario);

The data is being received in the result string and the Transmissao_rec class has the Arraylist methods.

1 answer

1


To convert data from JSON to object, I advise using the Gson that Voce is using or Libraries like the Retrofit that allow you to request and map Json directly to an object. But I suggest that in a first stage Cvoce do the Parsing "manually" using the class Jsonobject and Voce can have more control over all elements. A simple example of how to do this:

Imagine we have a string with a user’s response

"{"user":{"name":"john","age":19}}"

and that we have a User class with the same fields. To do Parsing : 1-Create a Json Object from the answer by passing the string : Jsonobject response = new Jsonobject(response);

2- We’ve got the user object : Jsonobject user = reply.getJSONObject("user"); Note that in this second call we use the first object of the answer and use the key of the object to pick up the object

3-We can take the name and age by doing String name = user.getString("name"); so on

4- With the attributes of our extracted object, just create a User instance and it is already.

I entered a lot through this process because it helps to realize mistakes made many times when using Ibraries where for example put one of the attributes in the class with the different name of keys in JSON that can result in an error.

See thiscode I wrote a few months ago to make the parse of JSON’s a little more complicated

Browser other questions tagged

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