问题
Here is my Json :
[
{
"canaldsc":"PHARMA",
"cadenadsc":null,
"formatodsc":"DEL AHORRO",
"estadodsc":null,
"ciudaddsc":"VALLE DE MEXICO",
"regiondsc":"CENTRO SUR",
"proyectotiendaid":null,
"proyectoid":"79",
"planid":"54",
"proyectodsc":"Concurso",
"vigencia":"0000-00-00",
"activo":"1",
"usuarioproyectotiendaid":"65280",
"proyecto":null,
"fechainicio":"2014-03-24",
"lunes":"7",
"martes":"7",
"miercoles":"7",
"jueves":"7",
"viernes":"7",
"sabado":"7",
"domingo":"7"
},
{
"canaldsc":"PHARMA",
"cadenadsc":null,
"formatodsc":"DEL AHORRO",
"estadodsc":null,
"ciudaddsc":"VALLE DE MEXICO",
"regiondsc":"CENTRO SUR",
"proyectotiendaid":null,
"proyectoid":"79",
"planid":"54",
"proyectodsc":"Concurso",
"vigencia":"0000-00-00",
"activo":"1",
"usuarioproyectotiendaid":"65284",
"proyecto":null,
"fechainicio":"2014-03-24",
"lunes":"7",
"martes":"7",
"miercoles":"7",
"jueves":"7",
"viernes":"7",
"sabado":"7",
"domingo":"7"
}
]
In reality, there is more than 2 objects, but I cut it to simplify
My Model Class :
public class PdvResult {
public PdvResult() {
}
public String canaldsc;
public String cadenadsc;
public String formatodsc;
public String estadodsc;
public String ciudaddsc;
public String regiondsc;
public String proyectotiendaid;
public String proyectoid;
public String planid;
public String proyectodsc;
public String vigencia;
public String activo;
public String usuarioproyectotiendaid;
public String proyecto;
public String fechainicio;
public String lunes;
public String martes;
public String miercoles;
public String jueves;
public String viernes;
public String sabado;
public String domingo;
}
It should be corresponds in the names so that the mapping can happen.
In my Java, I use
List<PdvResult> pdvs = (List<PdvResult>)gson.fromJson(reader, new TypeToken<PdvResult>() {}.getType());
but pdvs return null.
What's wrong with my code????
回答1:
Change the line where you parse the JSON, use this:
List<PdvResult> pdvs = gson.fromJson(reader, new TypeToken<List<PdvResult>>() {}.getType());
You are using TypeToken<PdvResult>, and you have to use TypeToken<List<PdvResult>>, otherwise you're trying to parse your JSON into a PdvResult object, while you actually have an array of PdvResult objects!
回答2:
The best way of checking the type of returned JSON object is explained below:
Start form
ObjectclassObject result= gson.fromJson(reader,Object.class); System.out.println(result.getClass().getName());It will return
java.lang.ArrayListDo the same operation of
ArrayListSystem.out.println(((ArrayList)result).size()); System.out.println(((ArrayList)result).get(0).getClass().getName());Now it will print the name of class stored in
ArrayList- Repeat the same operation till leaf nodes
- Finally form the resultant JSON object as expected by inspecting object and class type
来源:https://stackoverflow.com/questions/22720966/parse-json-with-gson-returns-null