List of usage examples for com.google.gson JsonElement isJsonPrimitive
public boolean isJsonPrimitive()
From source file:net.daporkchop.toobeetooteebot.text.JsonUtils.java
License:Open Source License
/** * Gets a human-readable description of the given JsonElement's type. For example: "a number (4)" *///from w ww . ja v a 2 s .c o m public static String toString(JsonElement json) { String s = org.apache.commons.lang3.StringUtils.abbreviateMiddle(String.valueOf(json), "...", 10); if (json == null) { return "null (missing)"; } else if (json.isJsonNull()) { return "null (json)"; } else if (json.isJsonArray()) { return "an array (" + s + ")"; } else if (json.isJsonObject()) { return "an object (" + s + ")"; } else { if (json.isJsonPrimitive()) { JsonPrimitive jsonprimitive = json.getAsJsonPrimitive(); if (jsonprimitive.isNumber()) { return "a number (" + s + ")"; } if (jsonprimitive.isBoolean()) { return "a boolean (" + s + ")"; } } return s; } }
From source file:net.doubledoordev.backend.util.JsonNBTHelper.java
License:Open Source License
public static Tag parseJSON(JsonElement element) { if (element.isJsonObject()) return parseJSON(element.getAsJsonObject()); else if (element.isJsonArray()) return parseJSON(element.getAsJsonArray()); else if (element.isJsonPrimitive()) return parseJSON(element.getAsJsonPrimitive()); return null;//from ww w . j a v a 2 s . co m }
From source file:net.kyori.text.serializer.gson.GsonComponentSerializer.java
License:MIT License
private BuildableComponent<?, ?> deserialize0(final JsonElement element, final JsonDeserializationContext context) throws JsonParseException { if (element.isJsonPrimitive()) { return TextComponent.of(element.getAsString()); } else if (element.isJsonArray()) { ComponentBuilder<?, ?> parent = null; for (final JsonElement childElement : element.getAsJsonArray()) { final BuildableComponent<?, ?> child = this.deserialize0(childElement, context); if (parent == null) { parent = child.toBuilder(); } else { parent.append(child);// w ww .j a v a 2 s .c o m } } if (parent == null) { throw new JsonParseException("Don't know how to turn " + element + " into a Component"); } return parent.build(); } else if (!element.isJsonObject()) { throw new JsonParseException("Don't know how to turn " + element + " into a Component"); } final JsonObject object = element.getAsJsonObject(); final ComponentBuilder<?, ?> component; if (object.has(TEXT)) { component = TextComponent.builder(object.get(TEXT).getAsString()); } else if (object.has(TRANSLATE)) { final String key = object.get(TRANSLATE).getAsString(); if (!object.has(TRANSLATE_WITH)) { component = TranslatableComponent.builder(key); } else { final JsonArray with = object.getAsJsonArray(TRANSLATE_WITH); final List<Component> args = new ArrayList<>(with.size()); for (int i = 0, size = with.size(); i < size; i++) { final JsonElement argElement = with.get(i); args.add(this.deserialize0(argElement, context)); } component = TranslatableComponent.builder(key).args(args); } } else if (object.has(SCORE)) { final JsonObject score = object.getAsJsonObject(SCORE); if (!score.has(SCORE_NAME) || !score.has(SCORE_OBJECTIVE)) { throw new JsonParseException( "A score component requires a " + SCORE_NAME + " and " + SCORE_OBJECTIVE); } // score components can have a value sometimes, let's grab it if (score.has(SCORE_VALUE)) { component = ScoreComponent.builder().name(score.get(SCORE_NAME).getAsString()) .objective(score.get(SCORE_OBJECTIVE).getAsString()) .value(score.get(SCORE_VALUE).getAsString()); } else { component = ScoreComponent.builder().name(score.get(SCORE_NAME).getAsString()) .objective(score.get(SCORE_OBJECTIVE).getAsString()); } } else if (object.has(SELECTOR)) { component = SelectorComponent.builder().pattern(object.get(SELECTOR).getAsString()); } else if (object.has(KEYBIND)) { component = KeybindComponent.builder().keybind(object.get(KEYBIND).getAsString()); } else if (object.has(NBT)) { final String nbt = object.get(NBT).getAsString(); final boolean interpret = object.has(NBT_INTERPRET) && object.getAsJsonPrimitive(NBT_INTERPRET).getAsBoolean(); if (object.has(NBT_BLOCK)) { final BlockNbtComponent.Pos position = context.deserialize(object.get(NBT_BLOCK), BlockNbtComponent.Pos.class); component = BlockNbtComponent.builder().nbtPath(nbt).interpret(interpret).pos(position); } else if (object.has(NBT_ENTITY)) { component = EntityNbtComponent.builder().nbtPath(nbt).interpret(interpret) .selector(object.get(NBT_ENTITY).getAsString()); } else { throw notSureHowToDeserialize(element); } } else { throw notSureHowToDeserialize(element); } if (object.has(EXTRA)) { final JsonArray extra = object.getAsJsonArray(EXTRA); for (int i = 0, size = extra.size(); i < size; i++) { final JsonElement extraElement = extra.get(i); component.append(this.deserialize0(extraElement, context)); } } final Style style = context.deserialize(element, Style.class); if (!style.isEmpty()) { component.style(style); } return component.build(); }
From source file:net.minecraftforge.client.model.MultiLayerModel.java
License:Open Source License
private ModelResourceLocation getLocation(String json) { JsonElement e = new JsonParser().parse(json); if (e.isJsonPrimitive() && e.getAsJsonPrimitive().isString()) { return new ModelResourceLocation(e.getAsString()); }/*from w w w . j av a 2s . c o m*/ FMLLog.severe("Expect ModelResourceLocation, got: ", json); return new ModelResourceLocation("builtin/missing", "missing"); }
From source file:net.nexustools.njs.JSON.java
License:Open Source License
public JSON(final Global global) { super(global); setHidden("stringify", new AbstractFunction(global) { public java.lang.String stringify(BaseObject object) { StringBuilder builder = new StringBuilder(); stringify(object, builder);//from www.jav a2 s . c om return builder.toString(); } public void stringify(BaseObject object, StringBuilder builder) { if (Utilities.isUndefined(object)) { builder.append("null"); return; } BaseObject toJSON = object.get("toJSON", OR_NULL); if (toJSON != null) stringify0(((BaseFunction) toJSON).call(object), builder); else stringify0(object, builder); } public void stringify0(BaseObject object, StringBuilder builder) { if (object instanceof GenericArray) { builder.append('['); if (((GenericArray) object).length() > 0) { stringify(object.get(0), builder); for (int i = 1; i < ((GenericArray) object).length(); i++) { builder.append(','); stringify(object.get(i), builder); } } builder.append(']'); } else if (object instanceof String.Instance) { builder.append('"'); builder.append(object.toString()); builder.append('"'); } else if (object instanceof Number.Instance) { double number = ((Number.Instance) object).value; if (Double.isNaN(number) || Double.isInfinite(number)) builder.append("null"); builder.append(object.toString()); } else if (object instanceof Boolean.Instance) builder.append(object.toString()); else { builder.append('{'); Iterator<java.lang.String> it = object.keys().iterator(); if (it.hasNext()) { java.lang.String key = it.next(); builder.append('"'); builder.append(key); builder.append("\":"); stringify(object.get(key), builder); if (it.hasNext()) { do { builder.append(','); key = it.next(); builder.append('"'); builder.append(key); builder.append("\":"); stringify(object.get(key), builder); } while (it.hasNext()); } } builder.append('}'); } } @Override public BaseObject call(BaseObject _this, BaseObject... params) { switch (params.length) { case 0: return Undefined.INSTANCE; case 1: if (params[0] == Undefined.INSTANCE) return Undefined.INSTANCE; return global.wrap(stringify(params[0])); default: return global.wrap("undefined"); } } @Override public java.lang.String name() { return "JSON_stringify"; } }); setHidden("parse", new AbstractFunction(global) { final Gson GSON; { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(BaseObject.class, new JsonDeserializer<BaseObject>() { @Override public BaseObject deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) throws JsonParseException { if (je.isJsonNull()) return Null.INSTANCE; if (je.isJsonPrimitive()) { JsonPrimitive primitive = je.getAsJsonPrimitive(); if (primitive.isBoolean()) return primitive.getAsBoolean() ? global.Boolean.TRUE : global.Boolean.FALSE; if (primitive.isNumber()) return global.wrap(primitive.getAsDouble()); if (primitive.isString()) return global.wrap(primitive.getAsString()); throw new UnsupportedOperationException(primitive.toString()); } if (je.isJsonObject()) { GenericObject go = new GenericObject(global); JsonObject jo = je.getAsJsonObject(); for (Map.Entry<java.lang.String, JsonElement> entry : jo.entrySet()) { go.set(entry.getKey(), deserialize(entry.getValue(), type, jdc)); } return go; } if (je.isJsonArray()) { JsonArray ja = je.getAsJsonArray(); BaseObject[] array = new BaseObject[ja.size()]; for (int i = 0; i < array.length; i++) { array[i] = deserialize(ja.get(i), type, jdc); } return new GenericArray(global, array); } throw new UnsupportedOperationException(je.toString()); } }); GSON = gsonBuilder.create(); } @Override public BaseObject call(BaseObject _this, BaseObject... params) { try { return GSON.fromJson(params[0].toString(), BaseObject.class); } catch (com.google.gson.JsonSyntaxException ex) { throw new Error.JavaException("SyntaxError", "Unexpected token", ex); } } @Override public java.lang.String name() { return "JSON_parse"; } }); }
From source file:net.oauth.jsontoken.JsonToken.java
License:Apache License
public JsonPrimitive getParamAsPrimitive(String param) { JsonElement element = payload.get(param); if (element != null && element.isJsonPrimitive()) { return (JsonPrimitive) element; }// www . ja va 2s. co m return null; }
From source file:net.praqma.tracey.tracey_rabbitmq_neo4j_bridge.Tracey2Neo.java
private void persistDataField(JsonElement elm, int id, String relationType) { if (elm.isJsonObject()) { parseJson(elm.getAsJsonObject(), id, relationType); }//from www. j a v a 2 s . c om // call this method again for all the elements in the array else if (elm.isJsonArray()) { JsonArray ja = elm.getAsJsonArray(); for (JsonElement jsonElement : ja) { persistDataField(jsonElement, id, relationType); } } // make an object out of the primitive to make a node in Neo4j else if (elm.isJsonPrimitive()) { JsonObject jo = new JsonObject(); jo.add("data", elm); persistDataField(jo, id, relationType); } }
From source file:net.praqma.tracey.tracey_rabbitmq_neo4j_bridge.Tracey2Neo.java
private Object getPrimitiveType(JsonElement jo) { if (!jo.isJsonPrimitive()) { return null; }/* www.j av a2s . c o m*/ JsonPrimitive jp = jo.getAsJsonPrimitive(); if (jp.isBoolean()) { return jp.getAsBoolean(); } if (jp.isNumber()) { return jp.getAsNumber(); } if (jp.isString()) { return jp.getAsString(); } return null; }
From source file:net.shibboleth.idp.oidc.flow.PreAuthorizeUserApprovalAction.java
License:Open Source License
/** * Gets user info claims for scopes.//from w w w. jav a 2 s. com * * @param sortedScopes the sorted scopes * @return the user info claims for scopes */ private Map<String, Map<String, String>> getUserInfoClaimsForScopes(final Set<SystemScope> sortedScopes) { final SecurityContext securityContext = SecurityContextHolder.getContext(); final Authentication authentication = securityContext.getAuthentication(); final SubjectContext context = (SubjectContext) authentication.getPrincipal(); final UserInfo user = userInfoService.getByUsername(context.getPrincipalName()); log.debug("Located UserInfo object from principal name {}", context.getPrincipalName()); final Map<String, Map<String, String>> claimsForScopes = new HashMap<>(); if (user != null) { final JsonObject userJson = user.toJson(); log.debug("UserInfo translated to JSON is:\n{}", userJson); for (final SystemScope systemScope : sortedScopes) { final Map<String, String> claimValues = new HashMap<>(); final Set<String> claims = scopeClaimTranslationService.getClaimsForScope(systemScope.getValue()); log.debug("Processing system scope {} for the following claims: {}", systemScope.getValue(), claims); for (final String claim : claims) { final JsonElement element = userJson.get(claim); if (userJson.has(claim) && element.isJsonPrimitive()) { claimValues.put(claim, element.getAsString()); log.debug("Added claim {} with value {}", claim, element.getAsString()); } } log.debug("Final claims for system scope {} are", systemScope.getValue(), claimValues); claimsForScopes.put(systemScope.getValue(), claimValues); } } return claimsForScopes; }
From source file:nl.talsmasoftware.enumerables.support.json.gson.EnumerableDeserializer.java
License:Apache License
public Enumerable deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { final Class<? extends Enumerable> enumerableType = enumerableSubTypeOf(type); if (json.isJsonNull()) return null; else if (json.isJsonPrimitive()) return Enumerable.parse(enumerableType, json.getAsString()); else if (json instanceof JsonObject) return Enumerable.parse(enumerableType, valueOf((JsonObject) json)); throw new IllegalStateException("Unable to parse JSON element as Enumerable object: " + json); }