2

I'm parsing json with Gson but I'm struggling with the data I'm getting. This is part of an API out of my control (openFDA) so changing that might not be an option.

Here's the json I'm strugling with: https://api.fda.gov/device/event.json?search=device.generic_name:generator&limit=10

There are some fields that are not consistent, for example remedial_action. Sometimes it comes out like this:

"remedial_action": [
        "Recall"
]

and in other results like this:

"remedial_action": ""

So it's either an array or a plain string. Is there a way to handle this? If not possible in Gson, any other json parsing library that can help?

I created my pojos here in case someone needs the code. There are a few files created from that and didn't want to spam them here. I can add them if needed.

Update: The bug has been confirmed and it's scheduled for a fix.

javydreamercsw
  • 5,363
  • 13
  • 61
  • 106

1 Answers1

2

It is possible through GSON, by using a TypeAdapter.

Here are the initial steps I would use to do that:

  1. Create a POJO that contains the array and the String. Let's call it RemedialAction.
  2. In your original POJO, create an attribute of the new class.
  3. Create a class that extends TypeAdapter<RemedialAction>.
  4. Override the read() and write() methods and create the logic in them.

That should be a little hard to parse, though. Read this tutorial for more information.

Note: you can customize getRemedialAction() to give you only the valid return -- array or String.

Paulo Avelar
  • 2,140
  • 1
  • 17
  • 31
  • Thanks! I still believe is a bug on their side. Filled an issue about it, but your answer is most likely the correct one. It just won't be pretty. https://github.com/FDA/openfda/issues/63 – javydreamercsw Sep 04 '15 at 17:56
  • Not really pretty, yes... let me know if it works and don't forget to mark it as correct if it does. :) – Paulo Avelar Sep 04 '15 at 18:10