是否存在支持嵌套对象的Java查询字符串解析器?
例如,我有以下查询字符串:
foo=bar&nested[attr]=found&nested[bar]=false
我想要这样的java地图(Map<String, Object>
):
list:
foo => bar
nested => list:
attr => found
bar => false
像这样生成json会很有用:
{"foo": "bar", "nested": {"attr": "found", "bar": false}}
答案 0 :(得分:0)
是的,有大量的JSON解析器,最简单的是JSONSimple,请点击此处:
https://www.mkyong.com/java/json-simple-example-read-and-write-json/
它可以处理嵌套对象(对象数组)和许多其他东西。就像您可以在链接上找到的那样,如果您需要将对象转换为JSON,请考虑使用更高级的东西,例如Jackson。
答案 1 :(得分:0)
让我们写一些代码来编码
{
filter: {
make: "honda";
model: "civic";
}
}
进入查询字符串 filter.make=honda&filter.model=civic
const { escape } = require("querystring");
function encode(queryObj, nesting = "") {
let queryString = "";
const pairs = Object.entries(queryObj).map(([key, val]) => {
// Handle the nested, recursive case, where the value to encode is an object
itself
if (typeof val === "object") {
return encode(val, nesting + `${key}.`);
} else {
// Handle base case, where the value to encode is simply a string.
return [nesting + key, val].map(escape).join("=");
}
});
return pairs.join("&");
}