我有这样的 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
的键值为 a
或b
此外,您将所有数据存储到 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/