Skip to content

Instantly share code, notes, and snippets.

@fge
Created May 31, 2013 23:38
Show Gist options
  • Save fge/5688657 to your computer and use it in GitHub Desktop.
Save fge/5688657 to your computer and use it in GitHub Desktop.
package com.github.fge.jsonschema;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.github.fge.jackson.JacksonUtils;
import com.github.fge.jackson.JsonLoader;
import com.github.fge.jackson.jsonpointer.JsonPointer;
import com.google.common.collect.Lists;
import java.io.IOException;
import java.util.List;
public final class Test
{
private static final JsonNode QUERY;
private static final JsonNode DATA;
static {
try {
QUERY = JsonLoader.fromResource("/query.json");
DATA = JsonLoader.fromResource("/data.json");
} catch (IOException e) {
throw new ExceptionInInitializerError(e);
}
}
private static List<JsonPointer> queryParamsToPointers(final JsonNode params)
{
// The core query params must be an array, if it is not, bail out
if (!params.isArray())
throw new IllegalArgumentException("expected an array here");
// jackson-coreutils depends on Guava, so we'll use that
final List<JsonPointer> ret = Lists.newArrayList();
for (final JsonNode node: params)
addQueryParam(JsonPointer.empty(), ret, node);
return ret;
}
private static void addQueryParam(final JsonPointer base,
final List<JsonPointer> ret, final JsonNode node)
{
if (!node.isArray())
throw new IllegalArgumentException("expected node to be an array");
final int size = node.size();
if (size == 0)
throw new IllegalArgumentException("expected at least one element");
if (arrayIsAllText(node)) {
for (final JsonNode element: node)
ret.add(base.append(element.textValue()));
return;
}
final JsonNode first = node.get(0);
if (!first.isTextual())
throw new IllegalArgumentException("first node is not a string");
final JsonPointer nextBase = base.append(first.textValue());
if (size == 1) {
ret.add(nextBase);
return;
}
addQueryParam(nextBase, ret, node.get(1));
}
private static boolean arrayIsAllText(final JsonNode node)
{
for (final JsonNode element: node)
if (!element.isTextual())
return false;
return true;
}
public static void main(final String... args)
{
final List<JsonPointer> pointers = queryParamsToPointers(QUERY);
final ArrayNode array = JacksonUtils.nodeFactory().arrayNode();
JsonNode node;
for (final JsonPointer ptr: pointers) {
node = ptr.get(DATA);
if (node != null)
array.add(node);
}
System.out.println(array);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment