简体   繁体   English

在Rest Service中返回动态Json

[英]Returning a dynamic Json in a Rest Service

I'm trying my hand on implementing a simple Restful Web Service using Spring Boot. 我正在尝试使用Spring Boot实现一个简单的Restful Web Service。

Currently, I want to parse an XML file to a Json object and return it as the response message. 当前,我想将XML文件解析为Json对象,并将其作为响应消息返回。 However I'm currently having problems defining the structure of the returned JSON object since it can vary depending on the XML file that I'm parsing. 但是,我目前在定义返回的JSON对象的结构时遇到问题,因为它可能因我解析的XML文件而异。

This is a parsed XML-to-Json example of what I'm trying to return. 这是我试图返回的XML解析为Json的示例。

{
    "App": {
        "CR": {
            "Product": {
                "PRequest": {
                    "MF": "dfl3",
                    "Pri": "0",
                    "PC": "age",
                    "PCode": "Hca"
                }
            }
        },
        "SD": {
            "SDF": {
                "PRP": {
                    "_cCao": "str1234",
                    "_cSao": "str1234",
                    "_dao": "2012-12-13",
                    "_dCao": "2012-12-13",
                    "_dr": "2012-12-13",
                    "_nIDta": "str1234",
                    "_no": "1234"
                }
            }
        }
    }
}

Is there a way to return a dynamic Json object whose structure is only defined at run time? 有没有办法返回仅在运行时定义结构的动态Json对象?

You can accomplish this very easily with org.json : 您可以使用org.json轻松完成此org.json

String xmlString = "<note><to>Bill</to><from>Ben</from><body>Hello!</body></note>";
JSONObject jsonObject = XML.toJSONObject(xmlString);
String jsonString = jsonObject.toString();

// Evaluates to:
// {"note":{"from":"Ben","to":"Bill","body":"Hello!"}}

This will turn an XML string into a JSONObject which you can then manipulate or turn into a JSON string. 这会将XML字符串转换为JSONObject,然后可以对其进行操作或将其转换为JSON字符串。

If you're using Maven, you can add a dependency for org.json by adding this to your pom.xml : 如果您使用的是Maven,则可以通过将其添加到pom.xml来为org.json添加依赖org.json

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20180813</version>
</dependency>

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

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