简体   繁体   English

将 URI 字符串解析为 JSON 对象

[英]Parse a URI String into a JSON object

I've got the URI like this:我有这样的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

I need a JSON object like this:我需要一个像这样的 JSON 对象:

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

Query parameters nesting can be dynamic, like for example abc.def.ghi.jkl.mno=value1&abc.xyz=value2 will result in查询参数嵌套可以是动态的,例如 abc.def.ghi.jkl.mno=value1&abc.xyz=value2 将导致

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

I have tried this but it can not handle the nesting.我试过这个,但它不能处理嵌套。

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

How to do this in Java?如何在 Java 中做到这一点?

With the way that your URI string is structured it wouldn't be possible to nest it the way you'd like, here's why.根据您的 URI 字符串的结构方式,不可能按照您喜欢的方式嵌套它,原因如下。

id=123 This is simple enough since id would just be an int id=123这很简单,因为 id 只是一个 int

productCategories.id=ICTLicense This would also be simple enough since we can assume that productCategories is an object and id is a key inside of the object productCategories.id=ICTLicense这也很简单,因为我们可以假设productCategories是一个对象,而id是对象内部的键

However, it gets more complex when you start using arrays, for instance: &groups=a&groups=b How do you know that groups is an array, and not simply a key called groups with a value of a or b然而,当你开始使用数组时,它会变得更加复杂,例如: &groups=a&groups=b你怎么知道groups是一个数组,而不仅仅是一个名为groups的键,其值为ab

Also, you store all your data to Map<String, String> , This wouldn't support arrays as it stores objects to key-value, so you wouldn't be able to have multiple keys of groups with different values.此外,您将所有数据存储到Map<String, String> ,这将不支持数组,因为它将对象存储到键值,因此您将无法拥有具有不同值的groups多个键。

I'd also suggest you use a library like Gson and parse your data to a JsonObject https://github.com/google/gson我还建议您使用像 Gson 这样的库并将您的数据解析为 JsonObject https://github.com/google/gson

If you were to use Gson, you could do something similar to this:如果你要使用 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