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

The following examples show how to use com.google.gson.JsonElement#getAsJsonObject() . 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: GsonDataTree.java    From helper with MIT License 6 votes vote down vote up
@Nonnull
@Override
public GsonDataTree resolve(@Nonnull Object... path) {
    if (path.length == 0) {
        return this;
    }

    JsonElement o = this.element;
    for (int i = 0; i < path.length; i++) {
        Object p = path[i];

        if (p instanceof String) {
            String memberName = (String) p;
            JsonObject obj = o.getAsJsonObject();
            if (!obj.has(memberName)) {
                throw new IllegalArgumentException("Object " + obj + " does not have member: " + memberName);
            }
            o = obj.get(memberName);
        } else if (p instanceof Number) {
            o = o.getAsJsonArray().get(((Number) p).intValue());
        } else {
            throw new IllegalArgumentException("Unknown path node at index " + i + ": " + p);
        }
    }
    return new GsonDataTree(o);
}
 
Example 2
Source File: QuerierDeserializer.java    From incubator-retired-pirk with Apache License 2.0 6 votes vote down vote up
@Override
public Querier deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException
{
  JsonObject jsonObject = jsonElement.getAsJsonObject();
  // Check the version number.
  long querierVersion = jsonObject.get("querierVersion").getAsLong();
  if (querierVersion != Querier.querierSerialVersionUID)
  {
    throw new JsonParseException(
        "Attempt to deserialize unsupported query version. Supported: " + Querier.querierSerialVersionUID + "; Received: " + querierVersion);
  }
  // Then deserialize the Query Info
  Query query = gson.fromJson(jsonObject.get("query").toString(), Query.class);

  // Now Paillier
  Paillier paillier = deserializePaillier(jsonObject.get("paillier").getAsJsonObject());

  List<String> selectors = gson.fromJson(jsonObject.get("selectors").toString(), new TypeToken<List<String>>()
  {}.getType());
  Map<Integer,String> embedSelectorMap = gson.fromJson(jsonObject.get("embedSelectorMap").toString(), new TypeToken<Map<Integer,String>>()
  {}.getType());

  return new Querier(selectors, paillier, query, embedSelectorMap);
}
 
Example 3
Source File: MolecularMatchObjectFactory.java    From hmftools with GNU General Public License v3.0 6 votes vote down vote up
@NotNull
private static List<MolecularMatchTierExplanation> createTierExplanations(@NotNull JsonArray tierExplanationArray) {
    List<MolecularMatchTierExplanation> tierExplanationList = Lists.newArrayList();
    ViccDatamodelChecker tierExplanationChecker = ViccDatamodelCheckerFactory.molecularMatchTierExplanationChecker();

    for (JsonElement tierExplanationElement : tierExplanationArray) {
        JsonObject tierExplanationObject = tierExplanationElement.getAsJsonObject();
        tierExplanationChecker.check(tierExplanationObject);

        tierExplanationList.add(ImmutableMolecularMatchTierExplanation.builder()
                .tier(string(tierExplanationObject, "tier"))
                .step(string(tierExplanationObject, "step"))
                .message(string(tierExplanationObject, "message"))
                .success(string(tierExplanationObject, "success"))
                .build());
    }
    return tierExplanationList;
}
 
Example 4
Source File: VariantSelectorData.java    From OpenModsLib with MIT License 6 votes vote down vote up
@Override
public VariantSelectorData deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
	final JsonObject jsonObject = json.getAsJsonObject();
	final Map<String, Matcher> matchers = Maps.newHashMap();
	final Set<ResourceLocation> allModels = Sets.newHashSet();

	for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) {
		final String name = e.getKey();
		final JsonElement value = e.getValue();

		final Matcher matcher;
		if (value.isJsonObject()) {
			matcher = createKeyedMatcher(name, e.getValue().getAsJsonObject());
		} else {
			matcher = createUnconditionalMatcher(name, e.getValue());
		}

		allModels.addAll(matcher.getAllModels());
		matchers.put(name, matcher);
	}

	final VariantSelectorData result = new VariantSelectorData();
	result.allModels = ImmutableSet.copyOf(allModels);
	result.matchers = ImmutableMap.copyOf(matchers);
	return result;
}
 
Example 5
Source File: AkashiDetailActivity.java    From kcanotify_h5-master with GNU General Public License v3.0 6 votes vote down vote up
private List<Integer> getImprovedCount(String equip_id) {
    JsonArray user_equipment_data = dbHelper.getItemData();
    List<Integer> count = new ArrayList<>(11);
    for (int i = 0; i <= 10; i++) count.add(0);

    for (JsonElement data: user_equipment_data) {
        JsonObject equip = data.getAsJsonObject();
        JsonObject value = new JsonParser().parse(equip.get("value").getAsString()).getAsJsonObject();
        String slotitem_id = value.get("api_slotitem_id").getAsString();
        int level = value.get("api_level").getAsInt();
        if (equip_id.equals(slotitem_id)) {
            count.set(level, count.get(level) + 1);
        }
    }
    return count;
}
 
Example 6
Source File: TwitchStream.java    From PneumaticCraft with GNU General Public License v3.0 6 votes vote down vote up
public void refresh(){
    try {
        url = new URL("https://api.twitch.tv/kraken/streams/" + channel);
        reader = new BufferedReader(new InputStreamReader(url.openStream()));

        // while((s = reader.readLine()) != null) {
        //   Log.info(s);
        JsonElement json = new JsonParser().parse(reader);
        JsonObject obj = json.getAsJsonObject();
        //   String title = obj.get("status").getAsString();
        JsonElement streaming = obj.get("stream");
        online = !streaming.isJsonNull();
        /* JsonArray array = json.getAsJsonArray();
         for(int i = 0; i < array.size(); i++) {
             Log.info(array.get(i).getAsString());
         }*/
        // Log.info(json.toString());
        // }

    } catch(Throwable e) {
        // e.printStackTrace();
    }
}
 
Example 7
Source File: QueryOptions.java    From yawp with MIT License 5 votes vote down vote up
private String getJsonStringValue(JsonElement jsonElement, String key) {
    JsonObject jsonObject = jsonElement.getAsJsonObject();
    if (!jsonObject.has(key)) {
        return null;
    }
    return jsonObject.get(key).getAsString();
}
 
Example 8
Source File: BlockRegion.java    From helper with MIT License 5 votes vote down vote up
public static BlockRegion deserialize(JsonElement element) {
    Preconditions.checkArgument(element.isJsonObject());
    JsonObject object = element.getAsJsonObject();

    Preconditions.checkArgument(object.has("min"));
    Preconditions.checkArgument(object.has("max"));

    BlockPosition a = BlockPosition.deserialize(object.get("min"));
    BlockPosition b = BlockPosition.deserialize(object.get("max"));

    return of(a, b);
}
 
Example 9
Source File: PlaceCheckinResultDeserializer.java    From ratebeer with GNU General Public License v3.0 5 votes vote down vote up
@Override
public PlaceCheckinResult deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
	JsonObject object = json.getAsJsonObject();
	// NOTE Success looks like:
	//   {"OK":"User has checked into The World of Drinks Krabbendijke ."}
	// NOTE Error looks like:
	//   {"Error":"User has already checked into The World of Drinks Krabbendijke recently."}
	PlaceCheckinResult placeCheckinResult = new PlaceCheckinResult();
	if (object.has("OK") && !(object.get("OK") instanceof JsonNull))
		placeCheckinResult.okResult = object.get("OK").getAsString();
	if (object.has("Error") && !(object.get("Error") instanceof JsonNull))
		placeCheckinResult.errorResult = object.get("Error").getAsString();
	return placeCheckinResult;
}
 
Example 10
Source File: RowImpl.java    From java-cloudant with Apache License 2.0 5 votes vote down vote up
RowImpl(ViewQueryParameters<K, V> parameters, JsonElement row) {
    this.parameters = parameters;
    this.gson = parameters.getClient().getGson();
    if (row.isJsonObject()) {
        this.row = row.getAsJsonObject();
    } else {
        this.row = new JsonObject();
    }
}
 
Example 11
Source File: BoundField.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * @return one of <code>InstanceRef</code> or <code>Sentinel</code>
 */
public InstanceRef getValue() {
  final JsonElement elem = json.get("value");
  if (!elem.isJsonObject()) return null;
  final JsonObject child = elem.getAsJsonObject();
  final String type = child.get("type").getAsString();
  if ("Sentinel".equals(type)) return null;
  return new InstanceRef(child);
}
 
Example 12
Source File: QuerySerializer.java    From quaerite with Apache License 2.0 5 votes vote down vote up
@Override
public Query deserialize(JsonElement jsonElement, Type type,
                         JsonDeserializationContext jsonDeserializationContext)
        throws JsonParseException {
    JsonObject root = jsonElement.getAsJsonObject();
    String queryType = JsonUtil.getSingleChildName(root);
    return buildQuery(queryType, root.getAsJsonObject(queryType));
}
 
Example 13
Source File: LiteralRangeSerializer.java    From datawave with Apache License 2.0 5 votes vote down vote up
@Override
public LiteralRange<String> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    JsonObject obj = json.getAsJsonObject();
    String fieldName = (obj.get("FN") == null ? null : obj.get("FN").getAsString());
    String lower = (obj.get("L") == null ? null : obj.get("L").getAsString());
    String upper = (obj.get("U") == null ? null : obj.get("U").getAsString());
    LiteralRange.NodeOperand operand = (obj.get("O") == null ? null : LiteralRange.NodeOperand.valueOf(obj.get("O").getAsString()));
    Boolean lowerInclusive = (obj.get("LI") == null ? null : obj.get("LI").getAsBoolean());
    Boolean upperInclusive = (obj.get("UI") == null ? null : obj.get("UI").getAsBoolean());
    
    return new LiteralRange<>(lower, lowerInclusive, upper, upperInclusive, fieldName, operand);
}
 
Example 14
Source File: JsonUtil.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
public static JsonObject getObject(JsonElement json) {
  if (json != null && json.isJsonObject()) {
    return json.getAsJsonObject();

  } else {
    return createObject();

  }
}
 
Example 15
Source File: JsonWorker.java    From ID-SDK with Apache License 2.0 5 votes vote down vote up
@Override
public Permission deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
		throws JsonParseException {
	 JsonObject obj = json.getAsJsonObject();
	 String identifier = null;
	 if(obj.get("handle") != null)
		 identifier = obj.get("handle").getAsString();
	 String perm = null;
	 if(obj.get("perm") != null)
		 perm = obj.get("perm").getAsString();
	return new Permission(identifier,perm);
}
 
Example 16
Source File: JsonRefCollector.java    From olca-app with Mozilla Public License 2.0 4 votes vote down vote up
private List<FlowRef> buildFlows(ZipFile zip) {
	List<FlowRef> flowRefs = new ArrayList<>();
	for (ZipEntry e : flowEntries) {
		JsonObject obj = unpack(e, zip);
		if (obj == null)
			continue;
		String id = Json.getString(obj, "@id");
		if (id == null)
			continue;
		FlowRef ref = new FlowRef();
		ref.flow = new FlowDescriptor();
		ref.flow.refId = id;
		ref.flow.name = Json.getString(obj, "name");
		ref.flow.flowType = Json.getEnum(obj, "flowType", FlowType.class);

		// the category
		String catID = Json.getRefId(obj, "category");
		ref.flowCategory = categoryPaths.get(catID);

		// find the reference flow property
		String propID = null;
		JsonArray props = Json.getArray(obj, "flowProperties");
		if (props != null) {
			for (JsonElement elem : props) {
				if (!elem.isJsonObject())
					continue;
				JsonObject prop = elem.getAsJsonObject();
				boolean isRef = Json.getBool(prop,
						"referenceFlowProperty", false);
				if (!isRef)
					continue;
				propID = Json.getRefId(prop, "flowProperty");
				break;
			}
		}
		if (propID != null) {
			ref.property = new FlowPropertyDescriptor();
			ref.property.refId = propID;
			ref.property.name = propertyNames.get(propID);

			String unitID = propertyUnits.get(propID);
			if (unitID != null) {
				ref.unit = new UnitDescriptor();
				ref.unit.refId = unitID;
				ref.unit.name = unitNames.get(unitID);
			}
		}
		flowRefs.add(ref);
	}
	return flowRefs;
}
 
Example 17
Source File: InsightsEmailService.java    From Insights with Apache License 2.0 4 votes vote down vote up
private String getFormattedEmailContent(JsonObject json, String emailTemplate) {

	JsonArray array = json.get(EmailConstants.DATA).getAsJsonArray();
	for(JsonElement element : array){
		
		int noOfPositives = 0;
		int noOfNegatives =0;
		int noOfNeutral= 0;
		ArrayList<String> positive=new ArrayList<>();
		ArrayList<String> negative=new ArrayList<>();
		ArrayList<String> neutral=new ArrayList<>();
		JsonObject output = element.getAsJsonObject();
		JsonArray arrayinfer = output.get(EmailConstants.INFERENCEDETAILS).getAsJsonArray();
		for(JsonElement elementinfer : arrayinfer){
			JsonObject outputinfer = elementinfer.getAsJsonObject();
			String sentiment=outputinfer.get(EmailConstants.SENTIMENT).getAsString() ;
			String inference=outputinfer.get("inference").getAsString() ;
			 if(EmailConstants.NEUTRAL.equals(sentiment)){
            	 noOfNeutral=noOfNeutral+1;
            	 neutral.add(inference);
            	
             }else if(EmailConstants.POSITIVE.equals(sentiment)){
            	 noOfPositives=noOfPositives+1;
            	 positive.add(inference);
            	
            	 
             }else if(EmailConstants.NEGATIVE.equals(sentiment)){
            	 noOfNegatives=noOfNegatives+1;
            	 negative.add(inference);
            	
             }
		}

		 element.getAsJsonObject().addProperty(EmailConstants.NOOFNEUTRAL,noOfNeutral);
		 element.getAsJsonObject().addProperty(EmailConstants.NOOFPOSITIVE,noOfPositives);
		 element.getAsJsonObject().addProperty(EmailConstants.NOOFNEGATIVE,noOfNegatives);
	}
	

	StringWriter stringWriter = EmailFormatter.getInstance().populateTemplate(array,emailTemplate);
	return stringWriter.toString();
}
 
Example 18
Source File: SiteActivityRender.java    From fenixedu-cms with GNU Lesser General Public License v3.0 4 votes vote down vote up
private static void pageCreated(SiteActivity activity, Writer writer) {
    JsonElement el = activity.getContent();
    JsonObject obj = el.getAsJsonObject();
    String postName = LocalizedString.fromJson(obj.get("pageName")).getContent();
    write(writer, obj.get("user").getAsString(), "created", postName);
}
 
Example 19
Source File: MainActivity.java    From kcanotify_h5-master with GNU General Public License v3.0 4 votes vote down vote up
private void loadDefaultAsset() {
    AssetManager am = getAssets();
    byte[] bytes;
    String kca_data_version = KcaUtils.getStringPreferences(getApplicationContext(), PREF_KCA_DATA_VERSION);
    String internal_kca_version = getString(R.string.default_gamedata_version);
    int currentKcaResVersion = dbHelper.getTotalResVer();
    try {
        if (kca_data_version == null || compareVersion(internal_kca_version, kca_data_version)) {
            InputStream api_ais = am.open("api_start2");
            bytes = gzipdecompress(ByteStreams.toByteArray(api_ais));
            String asset_start2_data = new String(bytes);
            dbHelper.putValue(DB_KEY_STARTDATA, asset_start2_data);
            KcaUtils.setPreferences(getApplicationContext(), PREF_KCA_VERSION, internal_kca_version);
            KcaUtils.setPreferences(getApplicationContext(), PREF_KCA_DATA_VERSION, internal_kca_version);
        }

        AssetManager.AssetInputStream ais = (AssetManager.AssetInputStream) am.open("list.json");
        bytes = ByteStreams.toByteArray(ais);
        JsonArray data = new JsonParser().parse(new String(bytes)).getAsJsonArray();

        for (JsonElement item: data) {
            JsonObject res_info = item.getAsJsonObject();
            String name = res_info.get("name").getAsString();
            int version = res_info.get("version").getAsInt();
            if (currentKcaResVersion < version) {
                final File root_dir = getDir("data", Context.MODE_PRIVATE);
                final File new_data = new File(root_dir, name);
                if (new_data.exists()) new_data.delete();
                InputStream file_is = am.open(name);
                OutputStream file_out = new FileOutputStream(new_data);

                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = file_is.read(buffer)) != -1) {
                    file_out.write(buffer, 0, bytesRead);
                }
                file_is.close();
                file_out.close();
                dbHelper.putResVer(name, version);
            }
        }
        ais.close();
    } catch (IOException e) {

    }
}
 
Example 20
Source File: View.java    From influxdb-client-java with MIT License 3 votes vote down vote up
@Override
public Object deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException {

  List<String> discriminator = Arrays.asList("timeFormat", "type", "shape");

  JsonObject jsonObject = json.getAsJsonObject();

  String[] types = discriminator.stream().map(jsonObject::get).filter(Objects::nonNull).map(JsonElement::getAsString).toArray(String[]::new);

  return deserialize(types, jsonObject, context);
}