when geting objects from a Json with restlet how can I get different objects in case the Json chnges its structure

一笑奈何 提交于 2019-12-12 01:32:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!