read a series of json elements (gson)

Asked

Viewed 105 times

-1

Next, I’m trying to write a java method that reads a series of json objects using Gogle’s gson. It’s just not working. I don’t know if it’s my code or my file, they’re both down there:

  • customer class:
public class Cliente {
    String id;
    String nome;
    String email;

    public Cliente() {
    }
}
  • method that reads the json and returns the client:
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class LerComGSON {


   public static Cliente json2java(){
       Gson gson = new Gson();
       try{
           BufferedReader br = new BufferedReader(new FileReader("clientes.json"));
           Cliente cliente = gson.fromJson(br, Cliente.class);
           return cliente;

       } catch (IOException  e){
           e.printStackTrace();
       }
       return null;
   }

}
  • json:
{   
    "CLIENTE1":{"ID":24828,"NOME":"Verona Boyer","EMAIL":"[email protected]"},
    "CLIENTE2":{"ID":33144,"NOME":"Rosetta Wuckert","EMAIL":"[email protected]"},
    "CLIENTE3":{"ID":67592,"NOME":"Tianna Runte II","EMAIL":"[email protected]"},
    "CLIENTE4":{"ID":38309,"NOME":"Howard Champlin","EMAIL":"[email protected]"}
}

the above code should read the first object "CLIENTE1" and return a client object with ID, NAME and EMAIL, but returns a client object with all empty fields

1 answer

0


You need to hit your customers.json:

[
  {
    "id": 24828,
    "nome": "Verona Boyer",
    "email": "[email protected]"
  },
  {
    "id": 33144,
    "nome": "Rosetta Wuckert",
    "email": "[email protected]"
  },
  {
    "id": 67592,
    "nome": "Tianna Runte II",
    "email": "[email protected]"
  },
  {
    "id": 38309,
    "nome": "Howard Champlin",
    "email": "[email protected]"
  }
]

Your json represents multiple clients. You need to get it right too:

Cliente[] clientes = gson.fromJson(br, Cliente[].class);

And consequently the return of your method:

public static Cliente[] json2java(){
  //ignorando o restante dos códigos.
}
  • It worked here man, thank you very much <3

Browser other questions tagged

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