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

The following examples show how to use com.google.gson.JsonElement#getClass() . 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: GsonUtils.java    From soul with Apache License 2.0 6 votes vote down vote up
/**
 * Get JsonElement class type.
 *
 * @param element the element
 * @return Class class
 */
public Class getType(final JsonElement element) {
    if (!element.isJsonPrimitive()) {
        return element.getClass();
    }
    
    final JsonPrimitive primitive = element.getAsJsonPrimitive();
    if (primitive.isString()) {
        return String.class;
    } else if (primitive.isNumber()) {
        String numStr = primitive.getAsString();
        if (numStr.contains(DOT) || numStr.contains(E)
                || numStr.contains("E")) {
            return Double.class;
        }
        return Long.class;
    } else if (primitive.isBoolean()) {
        return Boolean.class;
    } else {
        return element.getClass();
    }
}
 
Example 2
Source File: PluginTemplateController.java    From datax-web with Apache License 2.0 6 votes vote down vote up
private String parseLoopArr(String parent, Iterator<JsonElement> jsonElementIterator) {
    StringBuffer stringBuffer = new StringBuffer();
    while (jsonElementIterator.hasNext()) {
        JsonElement jsonElement = jsonElementIterator.next();

        if (jsonElement.getClass() == JsonObject.class) {
            parseLoop(parent, jsonElement.getAsJsonObject().entrySet());
        } else if (jsonElement.getClass() == JsonPrimitive.class) {
            System.out.println("444\t\t" + parent + "." + jsonElement.getAsJsonPrimitive().getAsString() + "=====");
            stringBuffer.append(jsonElement.toString() + ",");
            //stringBuffer.append(jsonElement.getAsJsonPrimitive().getAsString() + ",");
        } else if (jsonElement.getClass() == com.google.gson.JsonArray.class) {
            System.out.println("555\t\t" + jsonElement.toString());
            stringBuffer.append(parseLoopArr(parent, jsonElement.getAsJsonArray().iterator()));
        }
    }

    return stringBuffer.toString();
}
 
Example 3
Source File: GsonTypeSerializer.java    From helper with MIT License 6 votes vote down vote up
@Override
public void serialize(TypeToken<?> type, JsonElement from, ConfigurationNode to) throws ObjectMappingException {
    if (from.isJsonPrimitive()) {
        JsonPrimitive primitive = from.getAsJsonPrimitive();
        to.setValue(GsonConverters.IMMUTABLE.unwarpPrimitive(primitive));
    } else if (from.isJsonNull()) {
        to.setValue(null);
    } else if (from.isJsonArray()) {
        JsonArray array = from.getAsJsonArray();
        // ensure 'to' is a list node
        to.setValue(ImmutableList.of());
        for (JsonElement element : array) {
            serialize(TYPE, element, to.getAppendedNode());
        }
    } else if (from.isJsonObject()) {
        JsonObject object = from.getAsJsonObject();
        // ensure 'to' is a map node
        to.setValue(ImmutableMap.of());
        for (Map.Entry<String, JsonElement> ent : object.entrySet()) {
            serialize(TYPE, ent.getValue(), to.getNode(ent.getKey()));
        }
    } else {
        throw new ObjectMappingException("Unknown element type: " + from.getClass());
    }
}
 
Example 4
Source File: GsonUtil.java    From swellrt with Apache License 2.0 6 votes vote down vote up
/**
 * Unpack a JsonElement into the object type
 *
 * @param <T> The type to deserialize
 * @param object The object used to accept the pare result
 * @param valueObj The root of a tree of JsonElements or an indirection index
 * @param gson A Gson context
 * @param raw
 * @throws GsonException
 */
public static <T extends GsonSerializable> void
    extractJsonObject(T object, JsonElement valueObj, Gson gson, RawStringData raw)
    throws GsonException {
  if (valueObj.isJsonObject()) {
    object.fromGson(valueObj.getAsJsonObject(), gson, raw);
  } else if (valueObj.isJsonPrimitive()) {
    JsonPrimitive primitive = valueObj.getAsJsonPrimitive();
    String s = null;
    if (raw == null || !primitive.isString()) {
      throw new GsonException("Decoding " + valueObj + " as object " + object.getClass() +
          " with no RawStringData given");
    }
    s = raw.getString(valueObj.getAsString());
    GsonUtil.parseJson(object, gson, s, raw);
  } else {
    throw new GsonException("Cannot decode valueObject " + valueObj.getClass() +
        " as object " + object.getClass());
  }
}
 
Example 5
Source File: GsonUtil.java    From incubator-retired-wave with Apache License 2.0 6 votes vote down vote up
/**
 * Unpack a JsonElement into the object type
 *
 * @param <T> The type to deserialize
 * @param object The object used to accept the pare result
 * @param valueObj The root of a tree of JsonElements or an indirection index
 * @param gson A Gson context
 * @param raw
 * @throws GsonException
 */
public static <T extends GsonSerializable> void
    extractJsonObject(T object, JsonElement valueObj, Gson gson, RawStringData raw)
    throws GsonException {
  if (valueObj.isJsonObject()) {
    object.fromGson(valueObj.getAsJsonObject(), gson, raw);
  } else if (valueObj.isJsonPrimitive()) {
    JsonPrimitive primitive = valueObj.getAsJsonPrimitive();
    String s = null;
    if (raw == null || !primitive.isString()) {
      throw new GsonException("Decoding " + valueObj + " as object " + object.getClass() +
          " with no RawStringData given");
    }
    s = raw.getString(valueObj.getAsString());
    GsonUtil.parseJson(object, gson, s, raw);
  } else {
    throw new GsonException("Cannot decode valueObject " + valueObj.getClass() +
        " as object " + object.getClass());
  }
}
 
Example 6
Source File: JsonParserBase.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
protected JsonObject getJObject(JsonObject parent, String name) throws IOException {
  JsonElement j = parent.get(name);
  if (j == null) { 
    return null;
  }
  if (!(j instanceof JsonObject)) {
    throw new IOException("property "+name+" is a "+j.getClass()+" looking for an object");
  }
  return (JsonObject) j;
}
 
Example 7
Source File: JsonParserBase.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
protected JsonObject getJObject(JsonObject parent, String name) throws IOException {
  JsonElement j = parent.get(name);
  if (j == null) { 
    return null;
  }
  if (!(j instanceof JsonObject)) {
    throw new IOException("property "+name+" is a "+j.getClass()+" looking for an object");
  }
  return (JsonObject) j;
}
 
Example 8
Source File: JsonParserBase.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
protected JsonObject getJObject(JsonObject parent, String name) throws IOException {
  JsonElement j = parent.get(name);
  if (j == null) { 
    return null;
  }
  if (!(j instanceof JsonObject)) {
    throw new IOException("property "+name+" is a "+j.getClass()+" looking for an object");
  }
  return (JsonObject) j;
}
 
Example 9
Source File: PostMapValuesAdapter.java    From ambari-logsearch with Apache License 2.0 5 votes vote down vote up
@Override
public List<PostMapValuesImpl> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
  List<PostMapValuesImpl> vals = new ArrayList<>();
  if (json.isJsonArray()) {
    for (JsonElement e : json.getAsJsonArray()) {
      vals.add(createPostMapValues(e, context));
    }
  } else if (json.isJsonObject()) {
    vals.add(createPostMapValues(json, context));
  } else {
    throw new RuntimeException("Unexpected JSON type: " + json.getClass());
  }
  return vals;
}
 
Example 10
Source File: TypeAdapters.java    From letv with Apache License 2.0 5 votes vote down vote up
public void write(JsonWriter out, JsonElement value) throws IOException {
    if (value == null || value.isJsonNull()) {
        out.nullValue();
    } else if (value.isJsonPrimitive()) {
        JsonPrimitive primitive = value.getAsJsonPrimitive();
        if (primitive.isNumber()) {
            out.value(primitive.getAsNumber());
        } else if (primitive.isBoolean()) {
            out.value(primitive.getAsBoolean());
        } else {
            out.value(primitive.getAsString());
        }
    } else if (value.isJsonArray()) {
        out.beginArray();
        i$ = value.getAsJsonArray().iterator();
        while (i$.hasNext()) {
            write(out, (JsonElement) i$.next());
        }
        out.endArray();
    } else if (value.isJsonObject()) {
        out.beginObject();
        for (Entry<String, JsonElement> e : value.getAsJsonObject().entrySet()) {
            out.name((String) e.getKey());
            write(out, (JsonElement) e.getValue());
        }
        out.endObject();
    } else {
        throw new IllegalArgumentException("Couldn't write " + value.getClass());
    }
}
 
Example 11
Source File: QuestionListDeserializer.java    From slr-toolkit with Eclipse Public License 1.0 5 votes vote down vote up
public List<Question<?>> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext ctx) {
	List<Question<?>> vals = new LinkedList<Question<?>>();
	System.out.println("using deser");
	if (json.isJsonArray()) {
		for (JsonElement e : json.getAsJsonArray()) {
			vals.add((Question<?>) ctx.deserialize(e, Question.class));
		}
	} else if (json.isJsonObject()) {
		vals.add((Question<?>) ctx.deserialize(json, Question.class));
	} else {
		throw new RuntimeException("Unexpected JSON type: " + json.getClass());
	}
	return vals;
}
 
Example 12
Source File: Util.java    From azure-mobile-apps-android-client with Apache License 2.0 4 votes vote down vote up
public static boolean compareJson(JsonElement e1, JsonElement e2) {
    // NOTE: if every property defined in e1 is in e2, the objects are
    // considered equal.

    if (e1 == null && e2 == null) {
        return true;
    }

    if (e1 == null || e2 == null) {
        return false;
    }

    if (e1.getClass() != e2.getClass()) {
        return false;
    }

    if (e1 instanceof JsonPrimitive) {
        JsonPrimitive p1 = (JsonPrimitive) e1;
        JsonPrimitive p2 = (JsonPrimitive) e2;

        if (p1.isString()) {
            try {
                Date d1 = DateSerializer.deserialize(p1.getAsString());
                Date d2 = DateSerializer.deserialize(p2.getAsString());

                if (!d1.equals(d2) && !e1.equals(e2)) {
                    return false;
                }
            } catch (Throwable t) {
                if (!e1.equals(e2)) {
                    return false;
                }
            }
        } else if (!e1.equals(e2)) {
            return false;
        }
    } else if (e1 instanceof JsonArray) {
        JsonArray a1 = (JsonArray) e1;
        JsonArray a2 = (JsonArray) e2;

        if (a1.size() != a2.size()) {
            return false;
        }

        for (int i = 0; i < a1.size(); i++) {
            if (!compareJson(a1.get(i), a2.get(i))) {
                return false;
            }
        }
    } else if (e1 instanceof JsonObject) {
        JsonObject o1 = (JsonObject) e1;
        JsonObject o2 = (JsonObject) e2;

        Set<Entry<String, JsonElement>> entrySet1 = o1.entrySet();

        for (Entry<String, JsonElement> entry : entrySet1) {

            if (entry.getKey().toLowerCase(Locale.getDefault()).equals("id")) {
                continue;
            }

            String propertyName1 = entry.getKey();
            String propertyName2 = null;
            for (Entry<String, JsonElement> entry2 : o2.entrySet()) {

                if (propertyName1.toLowerCase(Locale.getDefault()).equals(entry2.getKey().toLowerCase(Locale.getDefault()))) {
                    propertyName2 = entry2.getKey();
                }
            }

            if (propertyName2 == null) {
                return false;
            }

            if (!compareJson(entry.getValue(), o2.get(propertyName2))) {
                return false;
            }
        }
    }

    return true;
}
 
Example 13
Source File: JsonStructureChecker.java    From MOE with Apache License 2.0 4 votes vote down vote up
private void requireSimilarNoKey(JsonElement a, JsonElement b) {
  if (a.getClass() == b.getClass()) {
    if (a instanceof JsonArray) {
      Iterator<JsonElement> aEls = ((JsonArray) a).iterator();
      Iterator<JsonElement> bEls = ((JsonArray) b).iterator();
      int index = 0;
      for (; aEls.hasNext() && bEls.hasNext(); ++index) {
        requireSimilar(index, aEls.next(), bEls.next());
      }
      if (aEls.hasNext() || bEls.hasNext()) {
        addKey(index);
        dissimilar();
      }
      return;
    } else if (a instanceof JsonObject) {
      Iterator<Map.Entry<String, JsonElement>> aProps = ((JsonObject) a).entrySet().iterator();
      Iterator<Map.Entry<String, JsonElement>> bProps = ((JsonObject) b).entrySet().iterator();
      // We don't ignore order of properties.
      while (aProps.hasNext() && bProps.hasNext()) {
        Map.Entry<String, JsonElement> aEntry = aProps.next();
        Map.Entry<String, JsonElement> bEntry = bProps.next();
        String aKey = aEntry.getKey();
        if (aKey.equals(bEntry.getKey())) {
          requireSimilar(aKey, aEntry.getValue(), bEntry.getValue());
        } else {
          addKey(aKey);
          dissimilar();
        }
      }
      if (aProps.hasNext()) {
        addKey(aProps.next().getKey());
        dissimilar();
      } else if (bProps.hasNext()) {
        addKey(bProps.next().getKey());
        dissimilar();
      }
      return;
    } else if (a instanceof JsonPrimitive) {
      // Ignore all number differences.  There are a number of
      // kinds of differences we want to ignore.
      // 1. (1I, 1L, 1D) are similar enough.
      // 2. (-0, +0)
      // 3. Small differences in decimal decoding.
      if (((JsonPrimitive) a).isNumber()
          && ((JsonPrimitive) b).isNumber()) {
        return;
      }
    }
  }
  if (!a.equals(b)) {
    dissimilar();
  }
}