我有一个使用AVRO自动生成的JSON schema类。我想使用这个JSON创建一个GSON对象。我尝试使用下面的代码来做到这一点
@Test
public void parseJson() {
JSONParser jsonParser = new JSONParser();
try {
JSONObject jsonObject = (JSONObject) jsonParser.parse(new FileReader("/pathto/test.json"));
ThinEvent thinEvent = new Gson().fromJson(jsonObject.toString(), ThinEvent.class);
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}但这会导致以下错误...它看起来像是GSON在寻找字符串,但是json实际上包含一个嵌套对象?ThinEvent对象将refService声明为列表。
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 74 path $.references[0].refServiceprivate java.util.List<com.lm.gde.eventing.avro.Reference> references;这是我的JSON,我用XXXX替换了一些值。
{
"eventType": "policy.PolicyPremiumChangedEvent",
"correlationId": "XXXX",
"references": [
{
"ref": "XXX",
"refType": "policy_id",
"refService": {
"com.lm.gde.eventing.avro.RefService": "policy_service"
},
"links": {
"array": [
{
"refUri": ""
}
]
}
},
{
"ref": "XXXXXX",
"refType": "policy_number",
"refService": {
"com.lm.gde.eventing.avro.RefService": "policy_service"
},
"links": {
"array": [
{
"refUri": "XXXXXX"
}
]
}
},
{
"ref": "2019-09-28",
"refType": "policy_tx_effective_date",
"refService": {
"com.lm.gde.eventing.avro.RefService": "policy_service"
},
"links": {
"array": [
{
"refUri": "XXXXX"
}
]
}
}
],
"eventContext": null,
"Timestamp": 1569574003295,
"Version": "1"
}发布于 2019-10-02 19:42:18
GSON支持嵌套对象check this article。只需创建与Json匹配的模型(但在Java/Kotlin中)并将其传递给GSON即可。Same with collections。您甚至可以使用List而不是array。
您可以将json文件作为一个完整的字符串获取,并对其进行反序列化。
https://stackoverflow.com/questions/58199077
复制相似问题