List of usage examples for com.google.gson JsonParser parse
@Deprecated public JsonElement parse(JsonReader json) throws JsonIOException, JsonSyntaxException
From source file:com.axlight.gbrain.server.GBrainServiceImpl.java
License:Apache License
public void fetchNeuron() throws IOException { URLFetchService ufs = URLFetchServiceFactory.getURLFetchService(); JsonParser parser = new JsonParser(); NeuronData[] targets = getTopNeurons(); for (NeuronData n : targets) { String q = URLEncoder.encode(n.getContent(), "UTF-8"); long parent = n.getId(); int x = n.getX(); int y = n.getY(); int children = n.getChildren(); HTTPResponse res = ufs// ww w.j a va 2s .c om .fetch(new URL("http://search.twitter.com/search.json?q=" + q + "&result_type=recent")); JsonElement top = parser.parse(new String(res.getContent(), "UTF-8")); for (JsonElement ele : top.getAsJsonObject().get("results").getAsJsonArray()) { String content = ele.getAsJsonObject().get("text").getAsString(); if (content.indexOf("http://") == -1) { continue; } if (alreadyExists(content)) { continue; } try { double deg = Math.random() * Math.PI * 2; int xx = x + (int) (Math.random() * PARAM_NEW_X * Math.cos(deg)); int yy = y + (int) (Math.random() * PARAM_NEW_Y * Math.sin(deg)); addNeuron(parent, content, xx, yy); children++; } catch (IllegalArgumentException e) { // ignored } } } }
From source file:com.baidu.cc.configuration.service.impl.VersionServiceImpl.java
License:Apache License
/** * ??./* w w w . ja v a 2 s .co m*/ * * @param file * * @param versionId * the version id * @throws IOException * ? */ @Override public void importFromFile(File file, Long versionId) throws IOException { byte[] byteArray = FileUtils.readFileToByteArray(file); Hex encoder = new Hex(); try { byteArray = encoder.decode(byteArray); } catch (DecoderException e) { throw new IOException(e.getMessage()); } String json = new String(byteArray, SysUtils.UTF_8); // parse from gson JsonParser jsonParser = new JsonParser(); JsonElement je = jsonParser.parse(json); if (!je.isJsonArray()) { throw new RuntimeException("illegal json string. must be json array."); } JsonArray jsonArray = je.getAsJsonArray(); int size = jsonArray.size(); Version version = new Version(); List<ConfigGroup> groups = new ArrayList<ConfigGroup>(); ConfigGroup group; List<ConfigItem> items; ConfigItem item; for (int i = 0; i < size; i++) { JsonObject jo = jsonArray.get(i).getAsJsonObject(); group = gson.fromJson(jo, ConfigGroup.class); // get sub configuration item JsonArray subItemsJson = jo.get(CONFIG_ITEMS_ELE).getAsJsonArray(); int subSize = subItemsJson.size(); items = new ArrayList<ConfigItem>(); for (int j = 0; j < subSize; j++) { item = gson.fromJson(subItemsJson.get(j), ConfigItem.class); items.add(item); } group.setConfigItems(items); groups.add(group); } version.setConfigGroups(groups); configCopyService.copyConfigItemsFromVersion(version, versionId); }
From source file:com.balajeetm.mystique.util.gson.lever.JsonComparator.java
License:Open Source License
/** * Checks if is subset./*from ww w . j av a 2 s . c om*/ * * @param subsetStr the subset str * @param actualStr the actual str * @return the myst result */ public Comparison isSubset(String subsetStr, String actualStr) { Comparison result = new Comparison(); JsonParser jsonParser = jsonLever.getJsonParser(); try { JsonElement actual = jsonParser.parse(actualStr); JsonElement subset = jsonParser.parse(subsetStr); isSubset("root", subset, actual, result); } catch (RuntimeException e) { result.setResult(Boolean.FALSE); result.addMsg(String.format("Exception % s occured", e.getMessage())); } return result; }
From source file:com.baomidou.springwind.util.yuntongxin.CCPRestSDK.java
License:Open Source License
/** * ???//from ww w .j a v a 2 s . com * * @param to * ? ??????????100 * @param templateId * ? ?Id * @param datas * ?? ???{??} * @return */ public HashMap<String, Object> sendTemplateSMS(String to, String templateId, String[] datas) { HashMap<String, Object> validate = accountValidate(); if (validate != null) return validate; if ((isEmpty(to)) || (isEmpty(App_ID)) || (isEmpty(templateId))) throw new IllegalArgumentException("?:" + (isEmpty(to) ? " ?? " : "") + (isEmpty(templateId) ? " ?Id " : "") + ""); CcopHttpClient chc = new CcopHttpClient(); DefaultHttpClient httpclient = null; try { httpclient = chc.registerSSL(SERVER_IP, "TLS", Integer.parseInt(SERVER_PORT), "https"); } catch (Exception e1) { e1.printStackTrace(); throw new RuntimeException("?httpclient" + e1.getMessage()); } String result = ""; try { HttpPost httppost = (HttpPost) getHttpRequestBase(1, TemplateSMS); String requsetbody = ""; if (BODY_TYPE == BodyType.Type_JSON) { JsonObject json = new JsonObject(); json.addProperty("appId", App_ID); json.addProperty("to", to); json.addProperty("templateId", templateId); if (datas != null) { StringBuilder sb = new StringBuilder("["); for (String s : datas) { sb.append("\"" + s + "\"" + ","); } sb.replace(sb.length() - 1, sb.length(), "]"); JsonParser parser = new JsonParser(); JsonArray Jarray = parser.parse(sb.toString()).getAsJsonArray(); json.add("datas", Jarray); } requsetbody = json.toString(); } else { StringBuilder sb = new StringBuilder("<?xml version='1.0' encoding='utf-8'?><TemplateSMS>"); sb.append("<appId>").append(App_ID).append("</appId>").append("<to>").append(to).append("</to>") .append("<templateId>").append(templateId).append("</templateId>"); if (datas != null) { sb.append("<datas>"); for (String s : datas) { sb.append("<data>").append(s).append("</data>"); } sb.append("</datas>"); } sb.append("</TemplateSMS>").toString(); requsetbody = sb.toString(); } //? System.out.println("" + requsetbody); logger.info("sendTemplateSMS Request body = " + requsetbody); BasicHttpEntity requestBody = new BasicHttpEntity(); requestBody.setContent(new ByteArrayInputStream(requsetbody.getBytes("UTF-8"))); requestBody.setContentLength(requsetbody.getBytes("UTF-8").length); httppost.setEntity(requestBody); HttpResponse response = httpclient.execute(httppost); //??? status = response.getStatusLine().getStatusCode(); System.out.println("Https??" + status); HttpEntity entity = response.getEntity(); if (entity != null) result = EntityUtils.toString(entity, "UTF-8"); EntityUtils.consume(entity); } catch (IOException e) { e.printStackTrace(); logger.error(e.getMessage()); return getMyError("172001", "" + "Https?" + status); } catch (Exception e) { e.printStackTrace(); logger.error(e.getMessage()); return getMyError("172002", ""); } finally { if (httpclient != null) httpclient.getConnectionManager().shutdown(); } logger.info("sendTemplateSMS response body = " + result); try { if (BODY_TYPE == BodyType.Type_JSON) { return jsonToMap(result); } else { return xmlToMap(result); } } catch (Exception e) { return getMyError("172003", ""); } }
From source file:com.baomidou.springwind.util.yuntongxin.CCPRestSDK.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 (Entry<String, JsonElement> m : entrySet) { if ("statusCode".equals(m.getKey()) || "statusMsg".equals(m.getKey())) hashMap.put(m.getKey(), m.getValue().getAsString()); else {/*from w w w .j av a 2 s.co m*/ if ("SubAccount".equals(m.getKey()) || "totalCount".equals(m.getKey()) || "smsTemplateList".equals(m.getKey()) || "token".equals(m.getKey()) || "callSid".equals(m.getKey()) || "state".equals(m.getKey()) || "downUrl".equals(m.getKey())) { if (!"SubAccount".equals(m.getKey()) && !"smsTemplateList".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 (Entry<String, JsonElement> m2 : entrySet2) { hashMap3.put(m2.getKey(), m2.getValue().getAsString()); } arrayList.add(hashMap3); } hashMap2.put(m.getKey(), 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 (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 (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.bedatadriven.rebar.appcache.server.DefaultSelectionServlet.java
License:Apache License
private JsonArray readPermutationMap(Path path) { try {/*from ww w. j av a 2 s . c o m*/ InputStreamReader reader = new InputStreamReader( new FileInputStream(getServletContext().getRealPath(path.moduleBase + "permutations"))); JsonParser parser = new JsonParser(); return (JsonArray) parser.parse(reader); } catch (FileNotFoundException e) { logger.info( "No permutations map found, (we are probably in dev mode) will return default selection script"); return null; } }
From source file:com.bicitools.ws.ConsumeServicios.java
public static RespuestaJson consumeTiempoDist(Object st) { RespuestaNuevoJson out = new RespuestaNuevoJson(); RespuestaJson output = new RespuestaJson(); try {/* w w w. j a va 2s .com*/ ClientConfig clientConfig = new DefaultClientConfig(); clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); Client client = Client.create(clientConfig); WebResource webResource = client.resource( "http://localhost:8080/bicitoolsRU/webresources/myresource/ObtenerDistanciaTiempoRuta"); ClientResponse response = webResource.accept("application/json").type("application/json") .post(ClientResponse.class, st); if (response.getStatus() != 200) { output = ConstruyeRespuesta.construyeRespuestaFalla("Fallo 200"); } String json = response.getEntity(String.class); Gson gson = new Gson(); JsonParser jParser = new JsonParser(); JsonObject jObject = (JsonObject) jParser.parse(json); JsonElement elem = jObject.get("codigo"); JsonElement elem2 = jObject.get("valor"); JsonElement elem3 = jObject.get("data"); JsonElement elem4 = jObject.get("descripcion"); JsonObject jObjectInterno = (JsonObject) jParser.parse(elem3.toString()); JsonElement elem5 = jObjectInterno.get("tiempo"); JsonElement elem6 = jObjectInterno.get("distancia"); TiempoDistanciaInfo t = new TiempoDistanciaInfo(elem5.toString(), elem6.toString()); ArrayList datos = new ArrayList(); //RespuestaNuevoJson info = gson.fromJson(json, RespuestaNuevoJson.class); //System.out.println(""); output.setCodigo(Integer.parseInt(elem.toString())); output.setValor(elem2.toString()); output.setDescripcion(elem4.toString()); datos.add(t); output.setDatos(datos); output.setDescripcion(out.getDescripcion()); } catch (Exception e) { output = ConstruyeRespuesta.construyeRespuestaFalla(e.getMessage()); e.printStackTrace(); } return output; }
From source file:com.bizideal.whoami.utils.cloopen.CCPRestSmsSDK.java
License:Open Source License
/** * ???/*from ww w . j a v a 2 s . c o m*/ * * @param to * ? ??????????100 * @param templateId * ? ?Id * @param datas * ?? ???{??} * @return */ public HashMap<String, Object> sendTemplateSMS(String to, String templateId, String[] datas) { HashMap<String, Object> validate = accountValidate(); if (validate != null) return validate; if ((isEmpty(to)) || (isEmpty(App_ID)) || (isEmpty(templateId))) throw new IllegalArgumentException("?:" + (isEmpty(to) ? " ?? " : "") + (isEmpty(templateId) ? " ?Id " : "") + ""); CcopHttpClient chc = new CcopHttpClient(); DefaultHttpClient httpclient = null; try { httpclient = chc.registerSSL(SERVER_IP, "TLS", Integer.parseInt(SERVER_PORT), "https"); } catch (Exception e1) { e1.printStackTrace(); throw new RuntimeException("?httpclient" + e1.getMessage()); } String result = ""; try { HttpPost httppost = (HttpPost) getHttpRequestBase(1, TemplateSMS); String requsetbody = ""; if (BODY_TYPE == BodyType.Type_JSON) { JsonObject json = new JsonObject(); json.addProperty("appId", App_ID); json.addProperty("to", to); json.addProperty("templateId", templateId); if (datas != null) { StringBuilder sb = new StringBuilder("["); for (String s : datas) { sb.append("\"" + s + "\"" + ","); } sb.replace(sb.length() - 1, sb.length(), "]"); JsonParser parser = new JsonParser(); JsonArray Jarray = parser.parse(sb.toString()).getAsJsonArray(); json.add("datas", Jarray); } requsetbody = json.toString(); } else { StringBuilder sb = new StringBuilder("<?xml version='1.0' encoding='utf-8'?><TemplateSMS>"); sb.append("<appId>").append(App_ID).append("</appId>").append("<to>").append(to).append("</to>") .append("<templateId>").append(templateId).append("</templateId>"); if (datas != null) { sb.append("<datas>"); for (String s : datas) { sb.append("<data>").append(s).append("</data>"); } sb.append("</datas>"); } sb.append("</TemplateSMS>").toString(); requsetbody = sb.toString(); } LoggerUtil.info("sendTemplateSMS Request body = " + requsetbody); BasicHttpEntity requestBody = new BasicHttpEntity(); requestBody.setContent(new ByteArrayInputStream(requsetbody.getBytes("UTF-8"))); requestBody.setContentLength(requsetbody.getBytes("UTF-8").length); httppost.setEntity(requestBody); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); if (entity != null) result = EntityUtils.toString(entity, "UTF-8"); EntityUtils.consume(entity); } catch (IOException e) { e.printStackTrace(); LoggerUtil.error(e.getMessage()); return getMyError("172001", ""); } catch (Exception e) { e.printStackTrace(); LoggerUtil.error(e.getMessage()); return getMyError("172002", ""); } finally { if (httpclient != null) httpclient.getConnectionManager().shutdown(); } LoggerUtil.info("sendTemplateSMS response body = " + result); try { if (BODY_TYPE == BodyType.Type_JSON) { return jsonToMap(result); } else { return xmlToMap(result); } } catch (Exception e) { return getMyError("172003", ""); } }
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 {/*from w ww. ja va 2 s. co m*/ 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();//from w w w .j a v a2 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); }