[英]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
的鍵,其值為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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.