简体   繁体   中英

Unmarshal nested JSON object to generic Java object

I'm using Jersey (2.5.1) for a RESTish API with JAXB to marshal JSON to/from POJOs. The client will be doing a POST with the following request:

{
   "type":"myevent",
   "data":{
       "id":"123",
       "count":2
    }
}

I have an 'Event' class which holds a type string and a data payload.

@XmlRootElement
public class Event {

    @XmlElement public String type;
    @XmlElement public JSONObject data;
    ...
}

The 'data' payload is a JSON object, however I don't know what type, or what the 'schema' of the object is. All I know is it's JSON. Above I have the type as a JSONObject, but that's just an example, maybe this needs to be Object? Map? Something else?

I want to be able to get the 'data' payload and persist this as JSON somewhere else.

I thought about using a String for the data payload, but then any API client would need to encode this and I would need to decode it before passing it on.

Any suggestions?

I usually work with strings on the backend side and then

    JSONObject json = new JSONObject(s); 

would create a json obj from that s (you don't need to decode).

On the client side I believe you just need to escape the " with something like a replaceAll function applied on that string

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