java - 将 URI 字符串解析为 JSON 对象

标签 java json spring spring-boot parsing

我有这样的 URI:

http://localhost:8080/profile/55cbd?id=123&type=product&productCategories.id=ICTLicense&productCategories.name.firstName=Jack&productCategories.name.lastName=Sparrow&groups=a&groups=b

我需要一个像这样的 JSON 对象:

{
  "id": "123",
  "type": "product",
  "productCategories": {
    "id": "ICTlicense",
    "name": {
      "firstName": "Jack",
      "lastName": "Sparrow"
    }
  },
  "groups":["a", "b"]
}

查询参数嵌套可以是动态的,例如 abc.def.ghi.jkl.mno=value1&abc.xyz=value2 将导致

{
  "abc": {
    "def": {
      "ghi": {
        "jkl": {
          "mno": "value1"
        }
      }
    },
    "xyz": "value2"
  }
}

我已经尝试过,但它无法处理嵌套。

final Map<String, String> map = Splitter.on('&').trimResults().withKeyValueSeparator('=').split(request.getQuery());

如何在 Java 中执行此操作?

最佳答案

按照 URI 字符串的结构方式,不可能按照您想要的方式嵌套它,原因如下。

id=123这很简单,因为 id 只是一个 int

productCategories.id=ICTLicense这也很简单,因为我们可以假设 productCategories是一个对象并且 id是对象内部的键

但是,当您开始使用数组时,它会变得更加复杂,例如: &groups=a&groups=b 你怎么知道groups是一个数组,而不仅仅是一个名为 groups 的键值为 ab

此外,您将所有数据存储到 Map<String, String> , 这不支持数组,因为它将对象存储为键值,因此您将无法拥有 groups 的多个键具有不同的值。

我还建议您使用像 Gson 这样的库并将数据解析为 JsonObject https://github.com/google/gson

如果您要使用 Gson,您可以执行类似的操作:

    public JsonObject convertToJson(String urlString) {
        //Create a JsonObject to store all our data to
        JsonObject json = new JsonObject();
        //Split the data part of the url by the props
        String[] props = urlString.split("&");

        //Loop through every prop in the url
        for (String prop : props) {
            //Create a list of all the props and nested props
            String[] nestedProps = prop.split("=")[0].split("\\.");
            //Get the actual key for our prop
            String key = nestedProps[nestedProps.length - 1];
            //Get the value
            String value = prop.split("=")[1];

            //Loop through our props array
            for (String nestedProp : nestedProps) {
                //If the property already exists, then skip
                if (json.has(nestedProp)) continue;

                //If the prop is the key, add it to the json object
                if(nestedProp.equalsIgnoreCase(key)) {
                    json.addProperty(nestedProp, value);
                    continue;
                }

                //If the above checks fail, then create an object in the json
                json.add(nestedProp, new JsonObject());
            }
        }

        return json;
    }

关于java - 将 URI 字符串解析为 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60981499/

相关文章:

javascript - 堆栈 ExtJS 6 + Spring Boot

java - 是什么导致了这个 NoClassDefFoundError 错误?

java - Java 中 MD5 的哈希值?

javascript - 在 AngularJS 中加载 JSON 数据之前出现 "loading"或 "wait"消息

javascript - 如何使用 javascript 在 JSON 中找到第二个键名

python - dask 包不使用所有内核?备择方案?

java - 疑似 JMS 队列资源泄漏 - 注入(inject)连接、 session 和队列

java - 在 JButton 中显示结果时出错

java - 我想知道如何在Jedis中用ShardedJedis遍历所有key?

java - Spring Boot - 流式传输 Apache FileUpload - 流意外结束