Skip to content

Commit

Permalink
Offer a threadsafe, easy to use shorthand for JSON-B fromJson(). IQSS…
Browse files Browse the repository at this point in the history
  • Loading branch information
poikilotherm committed Oct 24, 2020
1 parent d3ef947 commit b99da7f
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions src/main/java/edu/harvard/iq/dataverse/util/json/JsonUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,15 @@
import java.util.Collections;
import java.util.logging.Logger;
import javax.json.*;
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.json.stream.JsonGenerator;

public class JsonUtil {

private static final Logger logger = Logger.getLogger(JsonUtil.class.getCanonicalName());
private static JsonWriterFactory jsonWriterFactory = Json.createWriterFactory(Collections.singletonMap(JsonGenerator.PRETTY_PRINTING, true));
private static Jsonb jsonb = JsonbBuilder.create();

/**
* Make an attempt at pretty printing a String but will return the original
Expand Down Expand Up @@ -41,5 +44,36 @@ public static String prettyPrint(JsonStructure jsonStructure) {
}
return stringWriter.toString();
}

/**
* Get a primitive data value from a JSON Value or throw a {@link IllegalStateException}.
* Null-safe, returning empty string.
*/
public static String getPrimitiveAsString(JsonValue value) {
if (value == null || value.getValueType().equals(JsonValue.ValueType.NULL)) {
return "";
} else if (
! value.getValueType().equals(JsonValue.ValueType.ARRAY) &&
! value.getValueType().equals(JsonValue.ValueType.OBJECT) )
{
return value.toString();
} else {
throw new IllegalStateException("Not a primitive: "+value.toString());
}
}

/**
* Offering a shorthand for JSON-B binding use
*/
public static <T> T fromJson(String json, Class<T> toClass) {
return jsonb.fromJson(json, toClass);
}

/**
* Offer a shorthand for JSON-B binding use
*/
public static <T> T fromJson(JsonValue json, Class<T> toClass) {
return fromJson(json.toString(), toClass);
}

}

0 comments on commit b99da7f

Please sign in to comment.