How to handle uncertain Json using Java Jersey -


i got question today fellow colleague. let's got json string one:

{people:{name:carlos}} 

so got simple class handle json string, wich this:

@xmlrootelement class peoplehandler(){      public person people;  } 

it happens sometime json string provide list of persons, this:

{people:[{name:carlos}, {name:michel}]} 

my question is: how can change peoplehandler class manage kind of inputs, there annotation can help?

note: main problem can receive of json string exampled here. class must able support both.

note 2: don't have control on input, given web service. know check json , build copy list whenever there single object, looking more elegant solution.

you can jsondeserialize annotaion , 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;    } } 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -