For a project I receive a JSON object as a message from an API that might have various fields that is not consistent. So I use BasicJsonParser to map it using Map<String, Object>
map. Then I access the field by using map.get("fieldName")
. But recently I have a field that causes problems when I try to parse the JSON.
The JSON looks like:
{
"name" : "Charlie",
"school" : public elementary school",
"city": "New York,NY",
"problematicField" : "\u000l\u00033\u00007█\u00007[\u003d\" .... and so on for this field is kinda long,
"TIMESTAMP":{"timestamp: 2022-09-01 10:00:00.00000000000"}
}
I only need two fields above the problematic field and the TIMESTAMP field on the bottom. But since having that problematicField, the TIMESTAMP cannot be mapped and will be null.
What can I do to escape that problematicField (I cannot remove it from the API since it's not part of our org)?
Here is my code on how I parse it. The JSON above will be accessed as a String called message.
BasicJsonParser parser = new BasicJsonParser();
final Map<String,Object> map;
map = parser.parseMap(message);
String name = String.valueOf(map.get("name"));
String school = String.valueOf(map.get("school"));
String timeStamp = String.valueOf(map.get("TIMESTAMP"));
So, I can get a String value for name and school but not timestamp. Because timestamp is below the problematic field that is causing issues with me accessing it (right now the map.get for timestamp would return null) How would I resolve my issue?
Edit: After 3 days, I found the solution using the duplicated question "How to parse JSON in Java ". Thank you.