简体   繁体   English

将嵌套的JSON对象解组为通用Java对象

[英]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. 我正在将Jersey(2.5.1)与JAXB一起用于RESTish API,以将JSON封送至POJO或从POJO封送JSON。 The client will be doing a POST with the following request: 客户端将通过以下请求进行POST:

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

I have an 'Event' class which holds a type string and a data payload. 我有一个'Event'类,其中包含类型字符串和数据有效载荷。

@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. “数据”有效载荷是一个JSON对象,但是我不知道该对象的类型或“模式”是什么。 All I know is it's JSON. 我所知道的是JSON。 Above I have the type as a JSONObject, but that's just an example, maybe this needs to be Object? 上面我有一个JSONObject类型,但这只是一个例子,也许这需要是Object? Map? 地图? Something else? 还有吗

I want to be able to get the 'data' payload and persist this as JSON somewhere else. 我希望能够获取“数据”有效负载并将其作为JSON保留在其他地方。

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. 我曾考虑过使用String作为数据有效负载,但是任何API客户端都需要对此进行编码,并且在传递之前需要对其进行解码。

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). 会从s创建一个json obj(您不需要解码)。

On the client side I believe you just need to escape the " with something like a replaceAll function applied on that string 在客户端,我相信您只需要对字符串应用类似replaceAll函数来逃脱“

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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