From de224bb89a86e327e1c1564fb96773f6430074e7 Mon Sep 17 00:00:00 2001 From: Antonin Delpeuch Date: Wed, 3 Jan 2018 14:28:32 +0100 Subject: [PATCH] Add JacksonJsonizable --- .../wikidata/utils/JacksonJsonizable.java | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 extensions/wikidata/src/org/openrefine/wikidata/utils/JacksonJsonizable.java diff --git a/extensions/wikidata/src/org/openrefine/wikidata/utils/JacksonJsonizable.java b/extensions/wikidata/src/org/openrefine/wikidata/utils/JacksonJsonizable.java new file mode 100644 index 000000000..c23c923da --- /dev/null +++ b/extensions/wikidata/src/org/openrefine/wikidata/utils/JacksonJsonizable.java @@ -0,0 +1,58 @@ +package org.openrefine.wikidata.utils; + +import java.io.IOException; +import java.util.Properties; + +import org.json.JSONException; +import org.json.JSONWriter; +import org.json.JSONObject; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.google.refine.Jsonizable; + +/** + * This class is inefficient because it serializes the + * object to string and then deserializes it back. Unfortunately, + * this is the only simple way to bridge Jackson to org.json. + * This conversion should be removed when (if ?) we migrate OpenRefine + * a better JSON library. + * + * @author antonin + * + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public abstract class JacksonJsonizable implements Jsonizable { + + @Override + public void write(JSONWriter writer, Properties options) + throws JSONException { + ObjectMapper mapper = new ObjectMapper(); + try { + writer.value(new JSONObject(mapper.writeValueAsString(this))); + } catch (JsonProcessingException e) { + throw new JSONException(e.toString()); + } + } + + public static T fromJSONClass(JSONObject obj, Class klass) throws JSONException { + ObjectMapper mapper = new ObjectMapper(); + String json = obj.toString(); + try { + return mapper.readValue(json, klass); + } catch (JsonParseException e) { + e.printStackTrace(); + throw new JSONException(e.toString()); + } catch (JsonMappingException e) { + e.printStackTrace(); + throw new JSONException(e.toString()); + } catch (IOException e) { + throw new JSONException(e.toString()); + } + } + +}