我有一个带有URL的字符串和其他一些“ JSON格式”的文本。像这样:
String result = "https://somesite.com/generic-url/11 {'id':11,'checked':true,'geo':'0'}"
我知道这很奇怪...但是我必须丢弃字符串中的URL,并将其余数据转换为JSONObject。
我怎样才能做到这一点?
在将JSON转换为JSONObject方面,有几个可用的库,我常用的两个是Google的GSON 库和jackson-databind
就从字符串中提取JSON而言,您可以使用正则表达式来捕获第一个'{'及其后的所有内容作为捕获组的一部分,我希望这会起作用。类似^[^\{]*(.+)
的情况可能适用于您的情况。
例如,使用GSON:
Pattern jsonPattern = Pattern.compile("^[^\\{]*(.+)");
Matcher jsonMatcher = jsonPattern.matcher(result);
if (jsonMatcher.find())
{
String json = jsonMatcher.group(0);
JSONObject jsonObj = new JsonParser().parse(json).getAsJsonObject();
}
else
{
// Log that match was not found for result
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句