json将HOCON字符串转换为Java对象
我的一个Web服务返回以下Java字符串:
[
{
id=5d93532e77490b00013d8862,
app=null,
manufacturer=pearsonEducation,
bookUid=bookIsbn,
model=2019,
firmware=[1.0],
bookName=devotional,
accountLinking=mandatory
}
]
对于上面的字符串,我有一个等价的Java对象。我想将上面的java字符串类型转换成java对象
我无法键入cast,因为它是字符串,而不是对象。因此,我试图将Java字符串转换为JSON字符串,然后我可以将该字符串写入Java对象,但没有运气得到invalid character "="
异常
Can you change the web service to return JSON?
那是不可能的。他们没有改变合同。如果他们返回JSON,这将非常容易
# 1 楼答案
在我看来,我们将解析过程分为两步
在这个演示代码中,我选择regex作为格式化方法,选择fastjson作为JSON工具。你可以选择杰克逊或格森。此外,我删除了},您可以将其放回,然后将其解析到数组中
[
{# 2 楼答案
嗯,这肯定不是这里给出的最佳答案,但这是可能的,至少
通过像这样的小步操作
String
,以获得可以处理的Map<String, String>
。看这个例子,它非常基本:# 3 楼答案
web服务返回的格式有自己的名称HOCON。(您可以阅读更多关于它的信息here)
您不需要自定义解析器。不要试图重新发明轮子。 改用现有的
将此maven依赖项添加到项目中:
然后按如下方式解析响应:
还有一个选项可以将整个字符串解析为POJO:
不幸的是,这个解析器不允许
null
值。因此,您需要处理类型为com.typesafe.config.ConfigException.Null
的异常另一个选项是将
HOCON
字符串转换为JSON
:然后可以使用任何JSON到POJO映射器