GSON Expected BEGIN_ARRAY but was BEGIN_OBJECT

前端 未结 3 1706
你的背包
你的背包 2020-11-30 08:12

I\'m getting this error when I receive only one single item in a list. I\'m using Jersey in the server side REST Web service, I only get the error when the List returned one

3条回答
  •  醉酒成梦
    2020-11-30 08:35

    Basically, your web service is broken in terms of how it's replying. If there's only one object for project it's returning only an object instead of an array.

    MikO's answer solves the problem but another approach is encapsulating that logic in a custom deserializer:

    class MyDeserializer implements JsonDeserializer {
    
        @Override
        public ProjectContainer deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) throws JsonParseException {
    
            JsonObject jo = je.getAsJsonObject().getAsJsonObject("project");
            if (jo.isJsonArray()) {
                 return new Gson().fromJson(je, ProjectContainer.class);
            } else {
                 Project p = jdc.deserialize(jo, Project.class);
                 List pList = new ArrayList(1);
                 pList.add(p);
                 ProjectContainer pc = new ProjectContainer();
                 pc.setProjects(pList);
                 return pc;
            }
        }
    }
    

    Then you can use:

    Gson gson = new GsonBuilder()
                    .registerTypeAdapter(ProjectContainer.class, new MyDeserializer())
                    .build();
    ProjectContainer pContainer = gson.fromJson(myJson, ProjectContainer.class);
    

提交回复
热议问题