Is it possible to somehow convert a dynamic JSON object (No fixed schema) into a Java object?
For example, for first time, I can get the following JSON object at runtime:
{
"addressDetails": {
"homeAddresses": [
{
"houseNo": "1",
"city": "2"
}
],
"currentAddress": {
"houseNo": "1",
"city": "2"
}
},
"personalDetails": {
"birthDetails": {
"birthPlace": "1",
"birthMonth": "2"
}
},
"confidentialDetails": {
"birthDetails": {
"birthPlace": "1",
"birthMonth": "2"
}
},
"bankingDetails": {
"bankName": "1",
"bankAccountNo": 2
}
}
The next time, maybe with something like this:
{
"confidentialDetails": {
"birthDetails": {
"birthPlace": "1",
"birthMonth": "2"
}
},
"personalDetails": {
"birthDetails": {
"birthPlace": "1",
"birthMonth": "2"
}
}
}
How can I handle all these variations? Is it possible with Jackson/Gson or some other library?
I expect to find a solution which is very generic and can handle the different variations in JSON object gracefully.
3
Answers
You can deserialize it into
Map<String,Object>
ObjectMapper is from Jackson library
sidenote: Java is a typed language. If you do this, you will loose some benefits of the type check that language offers
I don’t know if I understand your question. However, you can try to define all possible JSON objects into one object and then serialize them using GSON or another JSON conversion tool.
like this:
Or if there are too many types to define, you can simply convert the JSON string to a JSON object for use
like this:
It is possible to do that with Jackson library. Just read the JSON and remove data with
addressDetails
andbankingDetails
keys.The output will be: