简体   繁体   中英

Parse a URI String into a JSON object

I've got the URI like this:

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:

{
  "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"
        }
      }
    },
    "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?

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.

id=123 This is simple enough since id would just be an 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

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

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.

I'd also suggest you use a library like Gson and parse your data to a JsonObject https://github.com/google/gson

If you were to use Gson, you could do something similar to this:

    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;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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