Java Code Examples for com.google.gson.JsonElement#isJsonObject()

The following examples show how to use com.google.gson.JsonElement#isJsonObject() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GsonJsonRpcUnmarshaller.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
private Object getInnerItem(JsonElement jsonElement) {
  if (jsonElement.isJsonNull()) {
    return null;
  }

  if (jsonElement.isJsonObject()) {
    return jsonElement.getAsJsonObject();
  }

  if (jsonElement.isJsonPrimitive()) {
    JsonPrimitive jsonPrimitive = jsonElement.getAsJsonPrimitive();
    if (jsonPrimitive.isNumber()) {
      return jsonPrimitive.getAsDouble();
    } else if (jsonPrimitive.isString()) {
      return jsonPrimitive.getAsString();
    } else {
      return jsonPrimitive.getAsBoolean();
    }
  }

  throw new IllegalStateException("Unexpected json element type");
}
 
Example 2
Source File: NeuralAnalyzer.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
private Data load_data(Business business, String job) throws Exception {
	EntityManager em = business.entityManagerContainer().get(Item.class);
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<Item> cq = cb.createQuery(Item.class);
	Root<Item> root = cq.from(Item.class);
	Predicate p = cb.equal(root.get(Item_.bundle), job);
	List<Item> list = em.createQuery(cq.where(p)).getResultList();
	if (list.isEmpty()) {
		return new Data();
	} else {
		JsonElement jsonElement = itemConverter.assemble(list);
		if (jsonElement.isJsonObject()) {
			return XGsonBuilder.instance().fromJson(jsonElement, Data.class);
		} else {
			return new Data();
		}
	}
}
 
Example 3
Source File: ActionCreate.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
ActionResult<Wo> execute(EffectivePerson effectivePerson, String processId, JsonElement jsonElement)
		throws Exception {

	ActionResult<Wo> result = new ActionResult<>();
	Wo wo = new Wo();
	Work work = null;
	try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
		Business business = new Business(emc);
		Process process = business.element().get(processId, Process.class);
		Application application = business.element().get(process.getApplication(), Application.class);
		Begin begin = business.element().getBeginWithProcess(process.getId());
		work = create(application, process, begin);
		emc.beginTransaction(Work.class);
		if ((null != jsonElement) && jsonElement.isJsonObject()) {
			WorkDataHelper workDataHelper = new WorkDataHelper(emc, work);
			workDataHelper.update(jsonElement);
		}
		emc.persist(work, CheckPersistType.all);
		emc.commit();
		wo.setId(work.getId());
	}
	MessageFactory.work_create(work);
	result.setData(wo);
	return result;
}
 
Example 4
Source File: MainView.java    From HiJson with Apache License 2.0 6 votes vote down vote up
/**
 * 处理jsoon对象.
 * @param obj
 * @param pNode
 */
private void createJsonObject(JsonObject obj, DefaultMutableTreeNode pNode){
    for(Map.Entry<String, JsonElement> el : obj.entrySet()){
        String key = el.getKey();
        JsonElement val = el.getValue();
        if(val.isJsonNull()){
            pNode.add(Kit.nullNode(key));
        }else if(val.isJsonArray()){
            createJsonArray(val.getAsJsonArray(),pNode,key);
        }else if(val.isJsonObject()){
            JsonObject child = val.getAsJsonObject();
            DefaultMutableTreeNode node = Kit.objNode(key);
            createJsonObject(child,node);
            pNode.add(node);
        }else if(val.isJsonPrimitive()){
            JsonPrimitive pri = val.getAsJsonPrimitive();
            formatJsonPrimitive(key,pri,pNode);
        }
    }

}
 
Example 5
Source File: JsonBuilder.java    From helper with MIT License 6 votes vote down vote up
@Override
public JsonObjectBuilder add(String property, @Nullable JsonElement value, boolean copy) {
    Objects.requireNonNull(property, "property");
    if (value == null) {
        value = nullValue();
    }

    if (copy && value.isJsonObject()) {
        this.handle.add(property, object(value.getAsJsonObject(), true).build());
    } else if (copy && value.isJsonArray()) {
        this.handle.add(property, array(value.getAsJsonArray(), true).build());
    } else {
        this.handle.add(property, value);
    }
    return this;
}
 
Example 6
Source File: SchemaValidator.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Replace $ref references with relevant schemas and recreate the swagger definition.
 *
 * @param parent Swagger definition parent Node
 * @throws APIManagementException Throws an APIManagement exception
 */
private void generateSchema(JsonElement parent) throws APIManagementException {
    JsonElement schemaProperty;
    Iterator<Map.Entry<String, JsonElement>> schemaNode;
    if (parent.isJsonArray()) {
        if (parent.getAsJsonArray().size() == 0) return;
        schemaNode = parent.getAsJsonArray().get(0).getAsJsonObject().entrySet().iterator();
    } else {
        schemaNode = parent.getAsJsonObject().entrySet().iterator();
    }
    while (schemaNode.hasNext()) {
        Map.Entry<String, JsonElement> entry = schemaNode.next();
        if (entry.getValue().isJsonObject() && entry.getValue().getAsJsonObject().has(APIMgtGatewayConstants.SCHEMA_REFERENCE)) {
            JsonObject refNode = entry.getValue().getAsJsonObject();
            for (Map.Entry<String, JsonElement> entryRef : refNode.entrySet()) {
                if (entryRef.getKey().equals(APIMgtGatewayConstants.SCHEMA_REFERENCE)) {
                    JsonElement schemaObject = extractSchemaObject(entryRef.getValue());
                    if (schemaObject != null) {
                        entry.setValue(schemaObject);
                    }
                }
            }
        }
        schemaProperty = entry.getValue();
        if (schemaProperty.isJsonObject()) {
            generateSchema(schemaProperty);
        }
        if (schemaProperty.isJsonArray()) {
            generateArraySchemas(entry);
        }
    }
}
 
Example 7
Source File: JsonStringToJsonIntermediateConverter.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * Parses a provided JsonObject input using the provided JsonArray schema into
 * a JsonObject.
 * @param record
 * @param schema
 * @return
 * @throws DataConversionException
 */
private JsonObject parse(JsonObject record, JsonSchema schema)
    throws DataConversionException {
    JsonObject output = new JsonObject();
    for (int i = 0; i < schema.fieldsCount(); i++) {
      JsonSchema schemaElement = schema.getFieldSchemaAt(i);
      String columnKey = schemaElement.getColumnName();
      JsonElement parsed;
      if (!record.has(columnKey)) {
        output.add(columnKey, JsonNull.INSTANCE);
        continue;
      }

      JsonElement columnValue = record.get(columnKey);
      switch (schemaElement.getType()) {
        case UNION:
          parsed = parseUnionType(schemaElement, columnValue);
          break;
        case ENUM:
          parsed = parseEnumType(schemaElement, columnValue);
          break;
        default:
          if (columnValue.isJsonArray()) {
            parsed = parseJsonArrayType(schemaElement, columnValue);
          } else if (columnValue.isJsonObject()) {
            parsed = parseJsonObjectType(schemaElement, columnValue);
          } else {
            parsed = parsePrimitiveType(schemaElement, columnValue);
          }
      }
      output.add(columnKey, parsed);
    }
    return output;
}
 
Example 8
Source File: GenericJsonDeserializer.java    From bender with Apache License 2.0 5 votes vote down vote up
private NestedData deserialize(JsonElement json) throws JsonParseException {
  final String messageStr = json.getAsString();
  /*
   * Find what might be JSON
   */
  int braceIndex = messageStr.indexOf('{');

  if (braceIndex == -1) {
    return new NestedData(json);
  }

  String maybeNestedJson = messageStr.substring(braceIndex);

  /*
   * Attempt to deserialize what we think might be JSON
   */
  JsonElement nestedJson;
  try {
    nestedJson = parser.parse(maybeNestedJson);
  } catch (Exception e) {
    return new NestedData(json);
  }

  /*
   * Only JSON objects are supported for MESSAGE payloads. No primitives or arrays.
   */
  if (!nestedJson.isJsonObject()) {
    return new NestedData(json);
  } else {
    return new NestedData(nestedJson.getAsJsonObject(), messageStr.substring(0, braceIndex));
  }
}
 
Example 9
Source File: JsonUtils.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Traverse the object graph starting at the given {@link JsonObject} along the properties defined by the given
 * property names and return the value of the last property.
 * <p>
 * Returns the given {@link JsonElement} if no property names are given. Returns <code>null</code> in case of error,
 * e.g. if the given {@code JsonElement} or any element encountered along the way isn't a {@code JsonObject} or in
 * case no property is found for one of the given property names.
 */
public static JsonElement getDeep(JsonElement jsonElement, String... propertyNames) {
	JsonElement curr = jsonElement;
	int i = 0;
	while (curr != null && i < propertyNames.length) {
		if (!curr.isJsonObject()) {
			return null;
		}
		curr = curr.getAsJsonObject().get(propertyNames[i++]);
	}
	return curr;
}
 
Example 10
Source File: KcaApiData.java    From kcanotify_h5-master with GNU General Public License v3.0 5 votes vote down vote up
public static int loadSortieExpInfoFromAssets(AssetManager am) {
    try {
        AssetManager.AssetInputStream ais = (AssetManager.AssetInputStream) am.open("exp_sortie.json");
        byte[] bytes = ByteStreams.toByteArray(ais);
        JsonElement expSortieData = new JsonParser().parse(new String(bytes));
        if (expSortieData.isJsonObject()) {
            helper.putValue(DB_KEY_EXPSORTIE, expSortieData.toString());
            return 1;
        } else {
            return -1;
        }
    } catch (IOException e) {
        return 0;
    }
}
 
Example 11
Source File: JsonConverter.java    From iotplatform with Apache License 2.0 5 votes vote down vote up
public static UpdateAttributesRequest convertToAttributes(JsonElement element, int requestId) {
  if (element.isJsonObject()) {
    BasicUpdateAttributesRequest request = new BasicUpdateAttributesRequest(requestId);
    long ts = System.currentTimeMillis();
    request.add(parseValues(element.getAsJsonObject()).stream().map(kv -> new BaseAttributeKvEntry(kv, ts))
        .collect(Collectors.toList()));
    return request;
  } else {
    throw new JsonSyntaxException("Can't parse value: " + element);
  }
}
 
Example 12
Source File: TopLevelResponse.java    From graphql_java_gen with MIT License 5 votes vote down vote up
public TopLevelResponse(JsonObject fields) throws InvalidGraphQLException {
    JsonElement errorsElement = fields.get(ERRORS_KEY);
    JsonElement dataElement = fields.get(DATA_KEY);
    if (dataElement != null && dataElement.isJsonNull()) {
        dataElement = null;
    }

    if (errorsElement == null && dataElement == null) {
        throw new InvalidGraphQLException("Response must contain a top-level 'data' or 'errors' entry");
    }

    if (dataElement != null) {
        if (!dataElement.isJsonObject()) {
            throw new InvalidGraphQLException("'data' entry in response must be a map");
        }
        this.data = dataElement.getAsJsonObject();
    }

    if (errorsElement != null) {
        if (!errorsElement.isJsonArray()) {
            throw new InvalidGraphQLException("'errors' entry in response must be an array");
        }
        for (JsonElement error : errorsElement.getAsJsonArray()) {
            errors.add(new Error(error.isJsonObject() ? error.getAsJsonObject() : new JsonObject()));
        }
    }
}
 
Example 13
Source File: Adapters.java    From activitystreams with Apache License 2.0 5 votes vote down vote up
public Table<?, ?, ?> deserialize(
  JsonElement json, 
  Type typeOfT,
  JsonDeserializationContext context) 
    throws JsonParseException {
  ImmutableTable.Builder<String,String,Object> table = 
    ImmutableTable.builder();
  checkArgument(json.isJsonObject());
  JsonObject obj = json.getAsJsonObject();
  for (Map.Entry<String,JsonElement> rowentry : obj.entrySet()) {
    String row = rowentry.getKey();
    JsonElement cell = rowentry.getValue();
    checkArgument(cell.isJsonObject());
    for (Map.Entry<String,JsonElement> cellentry : cell.getAsJsonObject().entrySet()) {
      String ckey = cellentry.getKey();
      JsonElement val = cellentry.getValue();
      Object desval = null;
      if (val.isJsonArray())
        desval = MultimapAdapter.arraydes(val.getAsJsonArray(),context);
      else if (val.isJsonObject())
        desval = context.deserialize(val, ASObject.class);
      else if (val.isJsonPrimitive())
        desval = primConverter.convert(val.getAsJsonPrimitive());
      if (desval != null)
        table.put(row,ckey,desval);
    }
  }
  return table.build();
}
 
Example 14
Source File: TestNNAnalyticsBase.java    From NNAnalytics with Apache License 2.0 5 votes vote down vote up
private static JsonArray getJsonDataArray(JsonObject json) {
  JsonArray datasets = json.getAsJsonArray("datasets");
  for (JsonElement next : datasets) {
    if (next.isJsonObject() && next.getAsJsonObject().has("data")) {
      return next.getAsJsonObject().get("data").getAsJsonArray();
    }
  }
  throw new IllegalStateException("No data found in histogram.");
}
 
Example 15
Source File: JsonConverter.java    From iotplatform with Apache License 2.0 5 votes vote down vote up
public static UpdateAttributesRequest convertToAttributes(JsonElement element, int requestId) {
  if (element.isJsonObject()) {
    BasicUpdateAttributesRequest request = new BasicUpdateAttributesRequest(requestId);
    long ts = System.currentTimeMillis();
    request.add(parseValues(element.getAsJsonObject()).stream().map(kv -> new BaseAttributeKvEntry(kv, ts))
        .collect(Collectors.toList()));
    return request;
  } else {
    throw new JsonSyntaxException("Can't parse value: " + element);
  }
}
 
Example 16
Source File: ResourceRecordSetsAdapter.java    From denominator with Apache License 2.0 5 votes vote down vote up
@Override
public Iterator<ResourceRecordSet<?>> build(JsonReader reader) throws IOException {
  JsonElement data;
  try {
    data = new JsonParser().parse(reader);
  } catch (JsonIOException e) {
    if (e.getCause() != null && e.getCause() instanceof IOException) {
      throw IOException.class.cast(e.getCause());
    }
    throw e;
  }

  // there are 2 forms for record responses: an array of same type, or a
  // map per type.
  if (data.isJsonArray()) {
    return new GroupByRecordNameAndTypeIterator(data.getAsJsonArray().iterator());
  } else if (data.isJsonObject()) {
    List<JsonElement> elements = new ArrayList<JsonElement>();
    for (Entry<String, JsonElement> entry : data.getAsJsonObject().entrySet()) {
      if (entry.getValue() instanceof JsonArray) {
        for (JsonElement element : entry.getValue().getAsJsonArray()) {
          elements.add(element);
        }
      }
    }
    return new GroupByRecordNameAndTypeIterator(elements.iterator());
  } else {
    throw new IllegalStateException("unknown format: " + data);
  }
}
 
Example 17
Source File: JsonObjectFlattenerImpl.java    From datawave with Apache License 2.0 4 votes vote down vote up
protected void addKeysToMap(String currentPath, JsonElement element, Multimap<String,String> map, Map<String,Integer> occurrenceCounts) {
    
    if (null == element || element.isJsonNull()) {
        // Don't add nulls
        return;
        
    } else if (element.isJsonObject()) {
        
        switch (this.flattenMode) {
            case SIMPLE:
                if (!currentPath.isEmpty()) {
                    // No recursion in simple mode
                    return;
                }
                break;
            case GROUPED:
            case GROUPED_AND_NORMAL:
                if (!currentPath.isEmpty()) {
                    // Append occurrence delimiter + ordinal suffix
                    currentPath = currentPath + this.occurrenceDelimiter + incrementCount(currentPath, occurrenceCounts);
                }
                break;
        }
        
        JsonObject jsonObject = element.getAsJsonObject();
        Iterator<Map.Entry<String,JsonElement>> iter = jsonObject.entrySet().iterator();
        String pathPrefix = currentPath.isEmpty() ? currentPath : currentPath + this.pathDelimiter;
        
        while (iter.hasNext()) {
            Map.Entry<String,JsonElement> entry = iter.next();
            addKeysToMap(pathPrefix + this.nameNormalizer.normalizeElementName(entry.getKey(), currentPath), entry.getValue(), map, occurrenceCounts);
        }
    } else if (element.isJsonArray()) {
        
        JsonArray jsonArray = element.getAsJsonArray();
        for (int i = 0; i < jsonArray.size(); i++) {
            
            if (jsonArray.get(i).isJsonPrimitive()) {
                mapPut(currentPath, jsonArray.get(i).getAsString(), map, occurrenceCounts);
            } else {
                
                if (this.addArrayIndexToFieldName) {
                    addKeysToMap(currentPath + this.pathDelimiter + i, jsonArray.get(i), map, occurrenceCounts);
                } else {
                    addKeysToMap(currentPath, jsonArray.get(i), map, occurrenceCounts);
                }
            }
        }
    } else if (element.isJsonPrimitive()) {
        
        JsonPrimitive primitive = element.getAsJsonPrimitive();
        mapPut(currentPath, primitive.getAsString(), map, occurrenceCounts);
    }
}
 
Example 18
Source File: JsonRpcResponseGsonAdaptor.java    From incubator-retired-wave with Apache License 2.0 4 votes vote down vote up
@Override
public JsonRpcResponse deserialize(JsonElement json, Type type,
    JsonDeserializationContext context) throws JsonParseException {
  JsonObject jsonObject = json.getAsJsonObject();

  String id = jsonObject.get(ResponseProperty.ID.key()).getAsString();
  if (jsonObject.has(ResponseProperty.ERROR.key())) {
    JsonElement errorObject = jsonObject.get(ResponseProperty.ERROR.key());
    String errorMessage = errorObject.getAsJsonObject().get("message").getAsString();
    return JsonRpcResponse.error(id, errorMessage);
  }

  // Deserialize the data.
  Map<ParamsProperty, Object> properties = new HashMap<ParamsProperty, Object>();
  JsonElement data = jsonObject.get(ResponseProperty.DATA.key());
  if (data != null && data.isJsonObject()) {
    for (Entry<String, JsonElement> parameter : data.getAsJsonObject().entrySet()) {
      ParamsProperty parameterType = ParamsProperty.fromKey(parameter.getKey());
      if (parameterType == null) {
        // Skip this unknown parameter.
        continue;
      }
      Object object = null;
      if (parameterType == ParamsProperty.BLIPS) {
        object = context.deserialize(parameter.getValue(), GsonFactory.BLIP_MAP_TYPE);
      } else if (parameterType == ParamsProperty.PARTICIPANTS_ADDED ||
          parameterType == ParamsProperty.PARTICIPANTS_REMOVED) {
        object = context.deserialize(parameter.getValue(), GsonFactory.PARTICIPANT_LIST_TYPE);
      } else if (parameterType == ParamsProperty.THREADS) {
        object = context.deserialize(parameter.getValue(), GsonFactory.THREAD_MAP_TYPE);
      } else if (parameterType == ParamsProperty.WAVELET_IDS) {
        object = context.deserialize(parameter.getValue(), GsonFactory.WAVELET_ID_LIST_TYPE);
      } else if (parameterType == ParamsProperty.RAW_DELTAS) {
        object = context.deserialize(parameter.getValue(), GsonFactory.RAW_DELTAS_TYPE);
      } else {
        object = context.deserialize(parameter.getValue(), parameterType.clazz());
      }
      properties.put(parameterType, object);
    }
  }

  return JsonRpcResponse.result(id, properties);
}
 
Example 19
Source File: RdapTestHelper.java    From nomulus with Apache License 2.0 4 votes vote down vote up
/** Writes down a human-readable diff between actual and expected into the StringBuilder. */
private void diff(
    String name, JsonElement actual, JsonElement expected, StringBuilder builder) {
  if (Objects.equals(actual, expected)) {
    return;
  }
  if (actual == null) {
    builder.append(String.format("Missing: %s ->%s\n\n", name, jsonifyAndIndent(expected)));
    return;
  }
  if (expected == null) {
    builder.append(String.format("Unexpected: %s -> %s\n\n", name, jsonifyAndIndent(actual)));
    return;
  }
  if (actual.isJsonObject() && expected.isJsonObject()) {
    // We put the "expected" first in the union so that the "expected" keys will all be first
    // and in order
    for (String key :
        Sets.union(expected.getAsJsonObject().keySet(), actual.getAsJsonObject().keySet())) {
      diff(
          name + "." + key,
          actual.getAsJsonObject().get(key),
          expected.getAsJsonObject().get(key),
          builder);
    }
    return;
  }
  if (actual.isJsonArray() && expected.isJsonArray()) {
    int commonSize = Math.max(actual.getAsJsonArray().size(), expected.getAsJsonArray().size());
    for (int i = 0; i < commonSize; i++) {
      diff(
          String.format("%s[%s]", name, i),
          getOrNull(actual.getAsJsonArray(), i),
          getOrNull(expected.getAsJsonArray(), i),
          builder);
    }
    return;
  }
  builder.append(
      String.format(
          "Different: %s -> %s\ninstead of %s\n\n",
          name, jsonifyAndIndent(actual), jsonifyAndIndent(expected)));
}
 
Example 20
Source File: HeosDeserializerEvent.java    From org.openhab.binding.heos with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public HeosResponseEvent deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    final JsonObject jsonObject;
    final JsonObject jsonHeos;

    if (json.isJsonObject()) {
        jsonObject = json.getAsJsonObject();
        jsonHeos = jsonObject.get("heos").getAsJsonObject();
    } else {
        return null;
    }

    // sets the Basic command String and decodes it afterwards to eventType and commandType
    this.rawCommand = jsonHeos.get("command").getAsString();
    decodeCommand(rawCommand);
    responseHeos.setCommand(rawCommand);
    responseHeos.setEventType(eventType);
    responseHeos.setCommandType(commandType);

    // not all Messages has a result field. Field is only set if check is true
    if (jsonHeos.has("result")) {
        this.rawResult = jsonHeos.get("result").getAsString();
        responseHeos.setResult(rawResult);
    } else {
        responseHeos.setResult("null");
    }
    // not all Messages has a message field. Field is only set if check is true
    if (jsonHeos.has("message")) {
        if (!jsonHeos.get("message").getAsString().isEmpty()) {
            this.rawMessage = jsonHeos.get("message").getAsString();
            responseHeos.setMessage(rawMessage); // raw Message
            decodeMessage(rawMessage);
            responseHeos.setMessagesMap(messages);
        } else {
            this.messages.put("command under process", "false");
            responseHeos.setMessagesMap(messages);
        }
    }
    if (rawResult.equals("fail")) {
        responseHeos.setErrorCode(messages.get("eid"));
        responseHeos.setErrorMessage(messages.get("text"));
    }
    return responseHeos;
}