简体   繁体   English

我可以在运行时创建JSON到Java POJO吗?

[英]Can I create JSON to Java POJO at runtime?

I have a requirement where I am getting the JSON response from REST API. 我有一个从REST API获取JSON响应的要求。

I can create a POJO and convert the JSON to JAVA but this particulat POJO is of no use for me in future or in other functionality. 我可以创建一个POJO并将JSON转换为JAVA,但是这个特殊的POJO在将来或其他功能上对我没有用。

Hence I was thinking to convert the JSON to Java dynamically using any API and render the objects in the JSP. 因此,我正在考虑使用任何API将JSON动态转换为Java,并在JSP中呈现对象。

Can you tell me is this a good practise and how can I do that? 您能告诉我这是一个好习惯吗,我该怎么做?

Expected JSON Response: 预期的JSON响应:

{
"_id": "",
"title": "",
"contact": "",
"country": "",
"children": [
   {
     "title": "",
      "contact": "",
      "country": "",
      "children": [
          {
            "title": "",
            "contact": "",
            "country": "",
            "children": []
           }
          ]
        }
      ]
     }

I don't think it is a good practice since doing the conversion to an actual Java POJO you are verifying the JSON is correct in some way according to what you expect to receive, not a real verification but better than nothing. 我不认为这是一个好习惯,因为您要转换为实际的Java POJO,这是根据您希望收到的内容以某种方式验证JSON的正确性,而不是真正的验证,总比没有好。

In any case, if you don't want to have an actual Java POJO you can use a Map<String,Object> to store the data and render it in the jsp, you can use Jackson library to accomplish that conversion. 无论如何,如果您不想使用实际的Java POJO,则可以使用Map <String,Object>来存储数据并将其呈现在jsp中,您可以使用Jackson库来完成该转换。

Regards. 问候。

UPDATE FOR QUESTION: 问题更新:

It looks quite simple with that schema, you can use the same class as parent and children, something like this: 该模式看起来非常简单,您可以使用与父级和子级相同的类,如下所示:

public class YourPojo implements Serializable {
    private String _id; // not good practice start by underscore
    private String title;
    private String contact;
    private String country;
    private List<YourPojo> children;

    // constructors, getters, setters...
}

Regards. 问候。

I would use an approach similar to what you have in XML: parse the JSON into a generic structure (DOM for XML) and then use configurable means to extract the data you are interested in eg XPath for XML or JSONPath for JSON. 我将使用与XML相似的方法:将JSON解析为通用结构(XML的DOM),然后使用可配置的方式提取您感兴趣的数据,例如XPath for XML或JSONPath for JSON。

This means you end up with code that can handle any well-formed JSON and that can be used to extract any part of the message through configuration. 这意味着您最终得到的代码可以处理任何格式正确的JSON,并且可以用于通过配置提取消息的任何部分。

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

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