List of usage examples for com.google.gson JsonElement getAsJsonObject
public JsonObject getAsJsonObject()
From source file:com.birbit.jsonapi.JsonApiLinksDeserializer.java
License:Apache License
@Override public JsonApiLinks deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { if (!json.isJsonObject()) { throw new JsonParseException("JsonApiLinks json element must be an object"); }/*from ww w .j a va2 s. c o m*/ JsonObject asJsonObject = json.getAsJsonObject(); Set<Map.Entry<String, JsonElement>> entries = asJsonObject.entrySet(); if (entries.isEmpty()) { return JsonApiLinks.EMPTY; } Map<String, JsonApiLinkItem> result = new HashMap<String, JsonApiLinkItem>(); for (Map.Entry<String, JsonElement> entry : asJsonObject.entrySet()) { JsonElement value = entry.getValue(); if (value.isJsonPrimitive()) { result.put(entry.getKey(), new JsonApiLinkItem(entry.getValue().getAsString())); } else { result.put(entry.getKey(), context.<JsonApiLinkItem>deserialize(entry.getValue(), JsonApiLinkItem.class)); } } return new JsonApiLinks(result); }
From source file:com.birbit.jsonapi.JsonApiResourceDeserializer.java
License:Apache License
@SuppressWarnings("WeakerAccess") public T deserialize(String id, JsonElement json, JsonDeserializationContext context) throws JsonParseException { if (!json.isJsonObject()) { throw new JsonParseException("expected a json object to parse into " + klass + " but received " + json); }//from www . j a va 2 s . co m T t = null; try { JsonObject jsonObject = json.getAsJsonObject(); t = parseObject(context, id, jsonObject); parseRelationships(context, t, jsonObject); parseLinks(context, t, jsonObject); } catch (IllegalAccessException e) { throw new JsonParseException("Cannot set ID/link on " + t, e); } catch (InvocationTargetException e) { throw new JsonParseException("Cannot set ID/link on " + t, e); } catch (InstantiationException e) { throw new JsonParseException( "Cannot create an instance of " + klass + ". Make sure it has a no-arg" + " constructor", e); } return t; }
From source file:com.birbit.jsonapi.JsonApiResourceDeserializer.java
License:Apache License
private void parseLinks(JsonDeserializationContext context, T t, JsonObject jsonObject) throws IllegalAccessException, InvocationTargetException { JsonElement links = jsonObject.get("links"); if (links != null && links.isJsonObject()) { JsonObject linksObject = links.getAsJsonObject(); Setter linksObjectSetter = linkSetters.get(""); if (linksObjectSetter != null) { linksObjectSetter.setOnObject(t, context.deserialize(links, JsonApiLinks.class)); }// w w w . j a v a 2 s . c o m for (Map.Entry<String, Setter> entry : linkSetters.entrySet()) { JsonElement link = linksObject.get(entry.getKey()); if (link != null && link.isJsonPrimitive()) { entry.getValue().setOnObject(t, link.getAsString()); } } } }
From source file:com.birbit.jsonapi.JsonApiResourceDeserializer.java
License:Apache License
private void parseRelationships(JsonDeserializationContext context, T t, JsonObject jsonObject) throws IllegalAccessException, InvocationTargetException { JsonElement relationships = jsonObject.get("relationships"); if (relationships != null && relationships.isJsonObject()) { JsonObject relationshipsObject = relationships.getAsJsonObject(); for (Map.Entry<String, Setter> entry : relationshipSetters.entrySet()) { JsonElement relationship = relationshipsObject.get(entry.getKey()); if (relationship != null && relationship.isJsonObject()) { if (entry.getValue().type() == JsonApiRelationshipList.class) { entry.getValue().setOnObject(t, context.deserialize(relationship, JsonApiRelationshipList.class)); } else if (entry.getValue().type() == JsonApiRelationship.class) { // JsonApiRelationship entry.getValue().setOnObject(t, context.deserialize(relationship, JsonApiRelationship.class)); } else { // String list or id JsonElement data = relationship.getAsJsonObject().get("data"); if (data != null) { if (data.isJsonObject()) { JsonElement relationshipIdElement = data.getAsJsonObject().get("id"); if (relationshipIdElement != null) { if (relationshipIdElement.isJsonPrimitive()) { entry.getValue().setOnObject(t, relationshipIdElement.getAsString()); }//from w w w . j a v a2 s.c o m } } else if (data.isJsonArray()) { List<String> idList = parseIds(data.getAsJsonArray()); entry.getValue().setOnObject(t, idList); } } } } } } }
From source file:com.birbit.jsonapi.JsonApiResourceDeserializer.java
License:Apache License
private List<String> parseIds(JsonArray jsonArray) { List<String> result = new ArrayList<String>(jsonArray.size()); for (int i = 0; i < jsonArray.size(); i++) { JsonElement item = jsonArray.get(i); if (item.isJsonObject()) { JsonElement idField = item.getAsJsonObject().get("id"); if (idField != null && idField.isJsonPrimitive()) { result.add(idField.getAsString()); }/*from ww w . ja va2s . co m*/ } } return result; }
From source file:com.bizideal.whoami.utils.cloopen.CCPRestSmsSDK.java
License:Open Source License
private HashMap<String, Object> jsonToMap(String result) { HashMap<String, Object> hashMap = new HashMap<String, Object>(); JsonParser parser = new JsonParser(); JsonObject asJsonObject = parser.parse(result).getAsJsonObject(); Set<Entry<String, JsonElement>> entrySet = asJsonObject.entrySet(); HashMap<String, Object> hashMap2 = new HashMap<String, Object>(); for (Map.Entry<String, JsonElement> m : entrySet) { if ("statusCode".equals(m.getKey()) || "statusMsg".equals(m.getKey())) hashMap.put(m.getKey(), m.getValue().getAsString()); else {/* w w w. j a v a2s. com*/ if ("SubAccount".equals(m.getKey()) || "totalCount".equals(m.getKey()) || "token".equals(m.getKey()) || "downUrl".equals(m.getKey())) { if (!"SubAccount".equals(m.getKey())) hashMap2.put(m.getKey(), m.getValue().getAsString()); else { try { if ((m.getValue().toString().trim().length() <= 2) && !m.getValue().toString().contains("[")) { hashMap2.put(m.getKey(), m.getValue().getAsString()); hashMap.put("data", hashMap2); break; } if (m.getValue().toString().contains("[]")) { hashMap2.put(m.getKey(), new JsonArray()); hashMap.put("data", hashMap2); continue; } JsonArray asJsonArray = parser.parse(m.getValue().toString()).getAsJsonArray(); ArrayList<HashMap<String, Object>> arrayList = new ArrayList<HashMap<String, Object>>(); for (JsonElement j : asJsonArray) { Set<Entry<String, JsonElement>> entrySet2 = j.getAsJsonObject().entrySet(); HashMap<String, Object> hashMap3 = new HashMap<String, Object>(); for (Map.Entry<String, JsonElement> m2 : entrySet2) { hashMap3.put(m2.getKey(), m2.getValue().getAsString()); } arrayList.add(hashMap3); } hashMap2.put("SubAccount", arrayList); } catch (Exception e) { JsonObject asJsonObject2 = parser.parse(m.getValue().toString()).getAsJsonObject(); Set<Entry<String, JsonElement>> entrySet2 = asJsonObject2.entrySet(); HashMap<String, Object> hashMap3 = new HashMap<String, Object>(); for (Map.Entry<String, JsonElement> m2 : entrySet2) { hashMap3.put(m2.getKey(), m2.getValue().getAsString()); } hashMap2.put(m.getKey(), hashMap3); hashMap.put("data", hashMap2); } } hashMap.put("data", hashMap2); } else { JsonObject asJsonObject2 = parser.parse(m.getValue().toString()).getAsJsonObject(); Set<Entry<String, JsonElement>> entrySet2 = asJsonObject2.entrySet(); HashMap<String, Object> hashMap3 = new HashMap<String, Object>(); for (Map.Entry<String, JsonElement> m2 : entrySet2) { hashMap3.put(m2.getKey(), m2.getValue().getAsString()); } if (hashMap3.size() != 0) { hashMap2.put(m.getKey(), hashMap3); } else { hashMap2.put(m.getKey(), m.getValue().getAsString()); } hashMap.put("data", hashMap2); } } } return hashMap; }
From source file:com.bizosys.dataservice.dao.WriteToXls.java
License:Apache License
public static void main(String[] args) throws Exception { String json = " { \"values\" : [ { \"name\" : \"ravi\" , \"id\" : \"334\" }, { \"name\" : \"kumar\" , \"id\" : \"335\" } ] }"; JsonParser parser = new JsonParser(); JsonObject o = (JsonObject) parser.parse(json); JsonArray values = o.getAsJsonArray("values"); Set<Map.Entry<String, JsonElement>> entrySet = null; List<Object[]> records = new ArrayList<Object[]>(); List<Object> cols = new ArrayList<Object>(); List<String> labels = new ArrayList<String>(); boolean isFirst = true; for (JsonElement elem : values) { JsonObject obj = elem.getAsJsonObject(); entrySet = obj.entrySet();/* w ww. j av a 2 s . c o m*/ cols.clear(); if (isFirst) { for (Map.Entry<String, JsonElement> entry : entrySet) { labels.add(entry.getKey()); } isFirst = false; } for (String aLabel : labels) { cols.add(obj.get(aLabel).getAsString()); } records.add(cols.toArray()); } OutputStream out = null; out = new FileOutputStream(new File("/tmp/test.xlsx")); WriteToXls writerXls = new WriteToXls(out, 0, 0); writerXls.write(records); }
From source file:com.bizosys.dataservice.sql.IdGenerator.java
License:Apache License
/** * * @param request ("{\"sequences\": [{\"sequence\": \"seq1\",\"amount\": 12},{\"sequence\": \"seq2\",\"amount\": 19},{\"sequence\": \"seq3\",\"amount\": 112}]}";) * @param response/*from w w w .j ava 2 s . c om*/ * @throws Exception */ public void generateIds(Request request, Response response) throws Exception { Gson gson = new Gson(); String json = request.getString("query", true, false, false); JsonElement jsonElem = gson.fromJson(json, JsonElement.class); JsonObject jsonObj = jsonElem.getAsJsonObject(); Iterator<JsonElement> queriesIterator = jsonObj.get(SEQUENCES_STRING).getAsJsonArray().iterator(); Map<String, Integer> sequences = new HashMap<String, Integer>(); while (queriesIterator.hasNext()) { JsonObject queryObj = (JsonObject) queriesIterator.next(); String seqId = queryObj.get(SEQUENCE_STRING).getAsString(); String amt = queryObj.get(AMOUNT_STR).getAsString(); int amount = -1; try { amount = Integer.parseInt(amt); } catch (NumberFormatException ex) { LOG.info("Sequence amount should be an integer", ex); response.setErrorCode(SEQUENCE_GENERATE_IDS, ErrorCodes.SEQUENCE_AMOUNT_ATLEAST_ONE, "en", true); } if (amount == 0) { response.setErrorCode(SEQUENCE_GENERATE_IDS, ErrorCodes.SEQUENCE_AMOUNT_ATLEAST_ONE, "en", true); return; } sequences.put(seqId, amount); } /** * FIND NEXT SEQUENCES */ boolean isError = false; Map<String, Integer> startIds = new HashMap<String, Integer>(); String poolName = request.getString("pool", false, false, true); IPool pool = (StringUtils.isEmpty(poolName)) ? PoolFactory.getDefaultPool() : PoolFactory.getInstance().getPool(poolName, false); Connection conn = null; PreparedStatement stmtU = null; PreparedStatement stmtS = null; ResultSet rs = null; String queryU = "update idsequence set sequenceno = sequenceno + ? where sequencename = ?"; String queryS = "select sequenceno from idsequence where sequencename = ?"; String idsequenceProccessing = null; try { conn = pool.getConnection(); conn.setAutoCommit(false); stmtU = conn.prepareStatement(queryU); stmtS = conn.prepareStatement(queryS); for (String idsequence : sequences.keySet()) { idsequenceProccessing = idsequence; stmtU.setInt(1, sequences.get(idsequence)); stmtU.setString(2, idsequence); stmtU.execute(); stmtS.setString(1, idsequence); stmtS.execute(); rs = stmtS.getResultSet(); if (rs.next()) { int startId = rs.getInt(1) - sequences.get(idsequence); startIds.put(idsequence, startId); } else { conn.rollback(); isError = true; startIds.clear(); LOG.warn("Sequence Id is not setup for :" + idsequence); response.setErrorMessage(SEQUENCE_GENERATE_IDS, ErrorCodes.SEQUENCE_ID_NOTSETUP, ErrorCodes.SEQUENCE_GENERATION_KEY, ErrorMessages.getInstance().getMessage( request.getUser().getLocale(), ErrorCodes.SEQUENCE_ID_NOTSETUP), true); } rs.close(); rs = null; } if (null != conn && !isError) conn.commit(); } catch (SQLException ex) { if (null != conn) conn.rollback(); LOG.warn("Error during id creation [" + idsequenceProccessing + "] under pool [" + poolName + "]", ex); throw ex; } finally { for (AutoCloseable resource : new AutoCloseable[] { rs, stmtS, stmtU, conn }) { try { if (null != resource) resource.close(); } catch (Exception ex) { LOG.warn(ex); } } } if (!isError) { /** * Send the Ids to client */ String formatType = request.getString("format", false, false, true); if (StringUtils.isEmpty(formatType)) formatType = "jsonp"; if (formatType.equals("jsonp")) { /** * MAKE JSON */ StringBuilder sb = new StringBuilder(128); boolean isFirst = true; sb.append("[{\"key\":\"").append(SEQUENCE_GENERATE_IDS) .append("\", \"type\" : \"SequenceGeneration\", \"values\" : ["); for (String seqId : startIds.keySet()) { if (isFirst) isFirst = false; else sb.append(','); sb.append("{\"").append(SEQUENCE_STRING).append("\":\"").append(seqId).append('"') .append(",\"start\":").append(startIds.get(seqId)).append("}"); } sb.append("],\"response\" : \"data\"}]"); response.writeTextWithHeaderAndFooter(sb.toString()); return; } else { response.setErrorMessage(SEQUENCE_GENERATE_IDS, ErrorCodes.INVALID_DATA_FORMAT, ErrorCodes.SEQUENCE_GENERATION_KEY, ErrorMessages.getInstance() .getMessage(request.getUser().getLocale(), ErrorCodes.INVALID_DATA_FORMAT), true); return; } } }
From source file:com.bizosys.dataservice.sql.KVPairsSerde.java
License:Apache License
public static final void deserJson(final String jsonStr, final Map<String, String> container) { if (StringUtils.isEmpty(jsonStr)) return;/* w ww.j a v a 2s .c o m*/ Gson gson = new Gson(); JsonElement jsonElem = gson.fromJson(jsonStr, JsonElement.class); JsonObject jsonObj = jsonElem.getAsJsonObject(); if (!jsonObj.has("variables")) return; Iterator<JsonElement> variablesIterator = jsonObj.get("variables").getAsJsonArray().iterator(); while (variablesIterator.hasNext()) { JsonObject variableObj = (JsonObject) variablesIterator.next(); if (variableObj.has("key") && variableObj.has("value")) { String varKey = variableObj.get("key").getAsString(); JsonElement obj = variableObj.get("value"); String varVal = (obj.isJsonNull()) ? null : obj.getAsString(); container.put(varKey, varVal); } } if (LOG.isDebugEnabled()) LOG.debug("Parsed variables are : " + container.toString()); }
From source file:com.bizosys.dataservice.sql.SqlSensorInputParser.java
License:Apache License
public static boolean fromJson(String queriesJson, List<UnitStep> queryUnits) throws ErrorCodeExp { Gson gson = new Gson(); JsonElement jsonElem = gson.fromJson(queriesJson, JsonElement.class); JsonObject jsonObj = jsonElem.getAsJsonObject(); Iterator<JsonElement> queriesIterator = jsonObj.get("queries").getAsJsonArray().iterator(); while (queriesIterator.hasNext()) { JsonObject queryObj = (JsonObject) queriesIterator.next(); /**/*ww w. j av a 2 s. c o m*/ * queryid */ if (queryObj.has("queryid")) { String queryId = queryObj.get("queryid").getAsString().trim(); addQuery(queryUnits, queryObj, queryId); } else if (queryObj.has("functionid")) { String functionId = queryObj.get("functionid").getAsString().trim(); addFunction(queryUnits, queryObj, functionId); } else if (queryObj.has("spid")) { String spId = queryObj.get("spid").getAsString().trim(); addSp(queryUnits, queryObj, spId); } } return true; }