我有以下类SolrFBLocationDoc
:
public class SolrFBLocationDoc{
@Field
private String name;
@Field
private String id;
@Field
private Location location = new Location();
//and some more class members
}
其中,Location
是来自restfb 的类:com.restfb.types.Location
。
我正在尝试将 solrDocument
转换为 SolrFBLocationDoc
类的对象,如下所示:
SolrFBLocationDoc doc = gson.fromJson(gson.toJson(solrDoc), SolrFBLocationDoc.class);
其中,solrDoc
是:
SolrDocument[{id=106377336067638, location=Location[city=null country=null latitude=null longitude=null state=null street=null zip=null]}]
和gson.toJson(solrDoc)
返回,
{"id":"106377336067638","location":"Location[city\u003dnull country\u003dnull latitude\u003dnull longitude\u003dnull state\u003dnull street\u003dnull zip\u003dnull]"}
但是,这会导致错误:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 166
我可以看到问题的发生是由于 gson.toJson(solrDoc)
将 Location
类对象转换为 String。
那么在不使用gson.toJson(solrDoc)
的情况下,如何将SolrDocument
转换为SolrFBLocationDoc
?
如何解决这个问题?
最佳答案
在您的 SolrFBLocationDoc
类中,location
ivar 属于 com.restfb.types.Location
类型,但在您的 JSON 字符串中:
"location":"Location[city\u003dnull country\u003dnull latitude\u003dnull longitude\u003dnull state\u003dnull street\u003dnull zip\u003dnull]"
表示location
是一个字符串。由于 SolrFBLocationDoc
定义,实际上,在分号之后,Gson 需要一个“{”(即 BEGIN_OBJECT
)。但它发现“Location..
,这是一个字符串,所以它不会解析。
正确的字符串如下:
{"id":"106377336067638","location":{"city":null, "country":null, "latitude":null, "longitude":null, "state":null, "street":null, "zip":null}}
因此,这意味着 gson.toJson(solrDoc)
返回您 location
键的转义字符串。这可能取决于 SolrDocument
的定义方式。可能在该类中 location
字段是一个字符串。如果您可以添加 SolrDocument
的定义,则可以完善此答案并确认/拒绝假设。
关于java - gson错误: com. google.gson.JsonSyntaxException : java. lang.IllegalStateException:预期为BEGIN_OBJECT,但在第1行第166列为STRING,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15807490/