I have a JSON schema class that is auto generate using AVRO. I would like to create a GSON object using this JSON. I try to do so using this code
@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();
}
}
but this results in the following error... It looks like GSON is looking for a string but the json actually contains a nested object? The ThinEvent object has refService declared as a list.
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 74 path $.references[0].refService
private java.util.List<com.lm.gde.eventing.avro.Reference> references;
Here is my JSON, I have replaced some values with 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"
}
GSON supports nested objects check this article . Just create model that matches the Json (but in Java/Kotlin) and toss it to GSON. Same with collections . You can even use List instead of arrays.
You could just get the json file as a complete string and deserialize that as well.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.