简体   繁体   中英

How to handle uncertain Json using Java Jersey

I got this question today from a fellow colleague. Let's say we got a Json String like this one:

{people:{name:Carlos}}

So I got a simple class to handle this Json String, wich will look something like this:

@XmlRootElement
class PeopleHandler(){

    public Person people;

}

It happens that sometime the Json String will provide a list of persons, like this:

{people:[{name:Carlos}, {name:Michel}]}

My question is: how can I change my PeopleHandler class to manage this kind of inputs, is there any annotation that can help?

NOTE : the main problem is that I can receive any of the Json String exampled here. So my class must be able to support both.

NOTE 2 : I don't have control over the input, it is given by a web service. I know I could check the Json and build a copy with list whenever there is a single object, but I was looking for a more elegant solution.

You can do it with JsonDeserialize annotaion and addition deserializer.
PeopleHandler.java

public class PeopleHandler 
{
   private List<Person> people;

   @JsonDeserialize(using = PersonDeserializer.class)
   public void setPeople(List<Person> o)
   {
      people = o;
   }

}  

PersonDeserializer.java

public class PersonDeserializer extends JsonDeserializer<List<Person>>
{
   @Override
   public List<Person> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException
   {
      List<Person> retVal = new ArrayList<Person>();
      if (jp.getCurrentToken() == JsonToken.START_OBJECT)
      {
         retVal.add(jp.readValueAs(Person.class));
      }
      else if (jp.getCurrentToken() == JsonToken.START_ARRAY)
      {
         while (jp.nextToken() == JsonToken.START_OBJECT)
         {
            retVal.add(jp.readValueAs(Person.class));
         }
      }

      return retVal;
   }
}

The JSON you've got there is actually an "array" of JSON objects. Hence, you might try making PeopleHandler use ArrayList< People> people;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM