001package org.tribuo.json; 002 003import com.fasterxml.jackson.databind.JsonNode; 004import com.fasterxml.jackson.databind.node.ObjectNode; 005 006import java.util.Collections; 007import java.util.HashMap; 008import java.util.Iterator; 009import java.util.Map; 010import java.util.logging.Logger; 011 012/** 013 * Utilities for interacting with JSON objects or text representations. 014 */ 015public final class JsonUtil { 016 017 private static final Logger logger = Logger.getLogger(JsonUtil.class.getName()); 018 019 /** 020 * Final class with private constructor 021 */ 022 private JsonUtil() {} 023 024 /** 025 * Converts a Json node into a Map from String to String for use in 026 * downstream processing by {@link org.tribuo.data.columnar.RowProcessor}. 027 * <p> 028 * This method ignores any fields which are not primitives (i.e., it ignores 029 * fields which are arrays and objects) as those are not supported 030 * by the columnar processing infrastructure. 031 * <p> 032 * If the node is null it returns Collections#emptyMap. 033 * @param node The json object to convert. 034 * @return The map representing this json node. 035 */ 036 public static Map<String,String> convertToMap(ObjectNode node) { 037 if (node != null) { 038 Map<String,String> entry = new HashMap<>(); 039 for (Iterator<Map.Entry<String, JsonNode>> itr = node.fields(); itr.hasNext(); ) { 040 Map.Entry<String, JsonNode> e = itr.next(); 041 if (e.getValue() != null) { 042 if (e.getValue().isValueNode()) { 043 entry.put(e.getKey(), e.getValue().asText()); 044 } else { 045 logger.warning("Ignoring key '" + e.getKey() + "' as it's value '" + e.getValue().asText() + "' is an object or array"); 046 } 047 } 048 } 049 return entry; 050 } else { 051 return Collections.emptyMap(); 052 } 053 } 054}