繁体   English   中英

将 URI 字符串解析为 JSON 对象

[英]Parse a URI String into a JSON object

我有这样的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;
    }

暂无
暂无

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

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