| Michael Hanl | ca740d7 | 2015-06-16 10:04:58 +0200 | [diff] [blame^] | 1 | package de.ids_mannheim.korap.utils; |
| 2 | |
| 3 | import com.fasterxml.jackson.core.JsonProcessingException; |
| 4 | import com.fasterxml.jackson.databind.JsonNode; |
| 5 | import com.fasterxml.jackson.databind.ObjectMapper; |
| 6 | import com.fasterxml.jackson.databind.node.ArrayNode; |
| 7 | import com.fasterxml.jackson.databind.node.ObjectNode; |
| 8 | |
| 9 | import java.io.File; |
| 10 | import java.io.IOException; |
| 11 | import java.util.ArrayList; |
| 12 | import java.util.Iterator; |
| 13 | import java.util.List; |
| 14 | import java.util.Map; |
| 15 | |
| 16 | /** |
| 17 | * @author hanl |
| 18 | * @date 28/01/2014 |
| 19 | */ |
| 20 | public class JsonUtils { |
| 21 | private static ObjectMapper mapper = new ObjectMapper(); |
| 22 | |
| 23 | private JsonUtils() { |
| 24 | } |
| 25 | |
| 26 | public static String toJSON(Object values) { |
| 27 | try { |
| 28 | return mapper.writeValueAsString(values); |
| 29 | }catch (JsonProcessingException e) { |
| 30 | return ""; |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | public static JsonNode readTree(String s) { |
| 35 | try { |
| 36 | return mapper.readTree(s); |
| 37 | }catch (IOException e) { |
| 38 | return null; |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | public static ObjectNode createObjectNode() { |
| 43 | return mapper.createObjectNode(); |
| 44 | } |
| 45 | |
| 46 | public static ArrayNode createArrayNode() { |
| 47 | return mapper.createArrayNode(); |
| 48 | } |
| 49 | |
| 50 | public static JsonNode valueToTree(Object value) { |
| 51 | return mapper.valueToTree(value); |
| 52 | } |
| 53 | |
| 54 | public static <T> T read(String json, Class<T> cl) throws IOException { |
| 55 | return mapper.readValue(json, cl); |
| 56 | } |
| 57 | |
| 58 | public static <T> T readFile(String path, Class<T> clazz) |
| 59 | throws IOException { |
| 60 | return mapper.readValue(new File(path), clazz); |
| 61 | } |
| 62 | |
| 63 | public static void writeFile(String path, String content) throws IOException { |
| 64 | mapper.writeValue(new File(path), content); |
| 65 | } |
| 66 | |
| 67 | public static <T> T readSimple(String json, Class<T> cl) { |
| 68 | try { |
| 69 | return mapper.readValue(json, cl); |
| 70 | }catch (IOException e) { |
| 71 | return null; |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | public static List<Map<String, Object>> convertToList(String json) |
| 76 | throws JsonProcessingException { |
| 77 | List d = new ArrayList(); |
| 78 | JsonNode node = JsonUtils.readTree(json); |
| 79 | if (node.isArray()) { |
| 80 | Iterator<JsonNode> nodes = node.iterator(); |
| 81 | while (nodes.hasNext()) { |
| 82 | Map<String, Object> map = mapper |
| 83 | .treeToValue(nodes.next(), Map.class); |
| 84 | d.add(map); |
| 85 | } |
| 86 | }else if (node.isObject()) { |
| 87 | Map<String, Object> map = mapper.treeToValue(node, Map.class); |
| 88 | d.add(map); |
| 89 | } |
| 90 | return d; |
| 91 | } |
| 92 | |
| 93 | } |