问题
I have a Json with some hierarchy, that at some point can change in its structure. The key OnOff can either have an object or an array, it can have an array like this:
"OnOff": [
{
"state": {
"last_update": 1401855332,
"value": "off"
}
}
]
Or it can only have an object, like this:
"OnOff":
{
"state": {
"last_update": 1401855332,
"value": "off"
}
}
The idea is to read the json and turn it into an object with Restlet for android. I'am using objects and interfaces, the class in the array case is defined by:
public class Capability {
public List<Processor> OnOff;// or Processor[]
public Capability(){}
}
and in the object case is defined by:
public class Capability {
public Processor OnOff;
public Capability(){}
}
Plus the interface and the code to retrieve the object.
Either definition will work on one of the jsons but not the other one. Is there a way of declaring a wrapper or something that can act as either array or object at the same time? Is there another approach for reading objects with restlet, like using maps?
Note: I really don't want to parse anything manually...
回答1:
You could call the Resource#toObject(representation, Target1.class|Target2.class) to try to convert to both classes.
But this isn't clear why you can simply rely on the second Capability class which can handle both single and multiple items. Maybe you don't control the server?
Another option is to add Jackson annotations, a base abstract Capability class and two subclasses https://github.com/FasterXML/jackson-annotations
来源:https://stackoverflow.com/questions/24050654/when-geting-objects-from-a-json-with-restlet-how-can-i-get-different-objects-in