Java Code Examples for com.google.gson.Gson#fromJson()

The following examples show how to use com.google.gson.Gson#fromJson() . 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: ClusterService.java    From karamel with Apache License 2.0 6 votes vote down vote up
public synchronized void startCluster(String json) throws KaramelException {
  Gson gson = new Gson();
  JsonCluster jsonCluster = gson.fromJson(json, JsonCluster.class);
  ClusterDefinitionValidator.validate(jsonCluster);
  String yml = ClusterDefinitionService.jsonToYaml(jsonCluster);
  //We have to do it again otherwise the global scope attributes get lost
  //for more info refer to https://github.com/karamelchef/karamel/issues/28
  jsonCluster = ClusterDefinitionService.yamlToJsonObject(yml);
  ClusterDefinitionService.saveYaml(yml);
  logger.debug(String.format("Let me see if I can start '%s' ...", jsonCluster.getName()));
  String clusterName = jsonCluster.getName();
  String name = clusterName.toLowerCase();
  if (repository.containsKey(name)) {
    logger.info(String.format("'%s' is already running :-|", jsonCluster.getName()));
    throw new KaramelException(String.format("Cluster '%s' is already running", clusterName));
  }
  ClusterContext checkedContext = checkContext(jsonCluster);
  ClusterManager cluster = new ClusterManager(jsonCluster, checkedContext);
  repository.put(name, cluster);
  cluster.start();
  cluster.enqueue(ClusterManager.Command.LAUNCH_CLUSTER);
  cluster.enqueue(ClusterManager.Command.SUBMIT_INSTALL_DAG);
}
 
Example 2
Source File: WebCollectionActivity.java    From Social with Apache License 2.0 6 votes vote down vote up
private void handleDeleteWebCollection(Message msg){
    String result = msg.obj.toString();
    Log.d("ShareRankFragment", result);
    Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
    DeleteWebCollectionRoot root = gson.fromJson(result, DeleteWebCollectionRoot.class);

    if (root == null){
        //new Dialog(this,"错误","链接服务器失败").show();
        Toast.makeText(this,"服务器繁忙,请重试",Toast.LENGTH_LONG).show();
        return;
    }

    if (root.success == false){
        new Dialog(this,"错误",root.message).show();
        return;
    }

    getWebcollectionList();

}
 
Example 3
Source File: PhotoWallParser.java    From Android-Application-ZJB with Apache License 2.0 6 votes vote down vote up
@Override
public List<Picture> parser(String json) {
    ArrayList<Picture> lists = new ArrayList<>();
    try {
        JSONArray array = new JSONArray(json);
        for (int i = 0; i < array.length(); i++) {
            JSONObject jsonObject = array.getJSONObject(i);
            String jsonString = jsonObject.toString();
            Gson gson = new Gson();
            Picture picture = gson.fromJson(jsonString, Picture.class);
            lists.add(picture);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return lists;
}
 
Example 4
Source File: NotifyInventoryUpdate.java    From inventory-hub-java-on-azure with MIT License 6 votes vote down vote up
@FunctionName("Notify-Inventory-Update")
public void notifyInventoryUpdate(
    @CosmosDBTrigger(name = "document", databaseName = "%NOTIFICATIONS_COSMOSDB_DBNAME%",
        collectionName = "%NOTIFICATIONS_COSMOSDB_COLLECTION_NAME%",
        connectionStringSetting = "NOTIFICATIONS_COSMOSDB_CONNECTION_STRING",
        leaseCollectionName = "%NOTIFY_INVENTORY_UPDATE_FUNCTION_APP_NAME%", createLeaseCollectionIfNotExists = true)
        String document,
    @EventHubOutput(name = "dataOutput", eventHubName = "%NOTIFICATIONS_EVENT_HUB_NAME%",
        connection = "NOTIFICATIONS_EVENT_HUB_CONNECTION_STRING") OutputBinding<String> dataOutput,
    final ExecutionContext context) {

    context.getLogger().info("Java CosmosDB Notification trigger processed a request: " + document);

    final Gson gson = new GsonBuilder().setPrettyPrinting().create();
    // We don't want to send the document content as is since it contains some properties we might not want
    List<TransactionEvent> transactionEvents = gson.fromJson(document, new TypeToken<ArrayList<TransactionEvent>>(){}.getType());

    context.getLogger().info("Creating Event Hub notifications: " + gson.toJson(transactionEvents));
    dataOutput.setValue(gson.toJson(transactionEvents));
}
 
Example 5
Source File: ATLASUtil.java    From Criteria2Query with Apache License 2.0 6 votes vote down vote up
public static List<Concept> searchConceptByName(String entity)
		throws UnsupportedEncodingException, IOException, ClientProtocolException {
	JSONObject queryjson = new JSONObject();
	queryjson.accumulate("QUERY", entity);
	System.out.println("queryjson:" + queryjson);
	String vocabularyresult = getConcept(queryjson);
	System.out.println("vocabularyresult  length=" + vocabularyresult.length());
	Gson gson = new Gson();
	JsonArray ja = new JsonParser().parse(vocabularyresult).getAsJsonArray();
	if (ja.size() == 0) {
		System.out.println("size=" + ja.size());
		return null;
	}
	List<Concept> list = gson.fromJson(ja, new TypeToken<List<Concept>>() {
	}.getType());
	return list;
}
 
Example 6
Source File: ExamPageAdmin.java    From ExamStack with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 学员试卷
 * @param model
 * @param request
 * @param examhistoryId
 * @return
 */
@RequestMapping(value = "/admin/exam/student-answer-sheet/{histId}", method = RequestMethod.GET)
private String studentAnswerSheetPage(Model model, HttpServletRequest request, @PathVariable int histId) {
	
	ExamHistory history = examService.getUserExamHistListByHistId(histId);
	int examPaperId = history.getExamPaperId();
	
	String strUrl = "http://" + request.getServerName() // 服务器地址
			+ ":" + request.getServerPort() + "/";
	
	ExamPaper examPaper = examPaperService.getExamPaperById(examPaperId);
	StringBuilder sb = new StringBuilder();
	if(examPaper.getContent() != null && !examPaper.getContent().equals("")){
		Gson gson = new Gson();
		String content = examPaper.getContent();
		List<QuestionQueryResult> questionList = gson.fromJson(content, new TypeToken<List<QuestionQueryResult>>(){}.getType());
		
		for(QuestionQueryResult question : questionList){
			QuestionAdapter adapter = new QuestionAdapter(question,strUrl);
			sb.append(adapter.getStringFromXML());
		}
	}
	
	model.addAttribute("htmlStr", sb);
	model.addAttribute("exampaperid", examPaperId);
	model.addAttribute("examHistoryId", history.getHistId());
	model.addAttribute("exampapername", examPaper.getName());
	model.addAttribute("examId", history.getExamId());
	return "student-answer-sheet";
}
 
Example 7
Source File: RestVNFPackage.java    From NFVO with Apache License 2.0 5 votes vote down vote up
@ApiOperation(
    value = "Adding a VNFPackage from the Package Repository",
    notes =
        "The JSON object in the request body contains a field named link, which holds the URL to the package on the Open Baton Marketplace")
@RequestMapping(
    value = "/package-repository-download",
    method = RequestMethod.POST,
    consumes = MediaType.APPLICATION_JSON_VALUE)
public String packageRepositoryDownload(
    @RequestBody JsonObject link, @RequestHeader(value = "project-id") String projectId)
    throws IOException, PluginException, VimException, NotFoundException, IncompatibleVNFPackage,
        AlreadyExistingException, NetworkServiceIntegrityException, BadRequestException,
        EntityUnreachableException, InterruptedException {
  Gson gson = new Gson();
  JsonObject jsonObject = gson.fromJson(link, JsonObject.class);
  if (!jsonObject.has("link"))
    throw new BadRequestException("The sent Json has to contain a field named: link");

  String downloadlink;
  try {
    downloadlink = jsonObject.getAsJsonPrimitive("link").getAsString();
  } catch (Exception e) {
    e.printStackTrace();
    throw new BadRequestException("The provided link has to be a string.");
  }
  VirtualNetworkFunctionDescriptor virtualNetworkFunctionDescriptor =
      vnfPackageManagement.onboardFromPackageRepository(downloadlink, projectId);
  return "{ \"id\": \"" + virtualNetworkFunctionDescriptor.getVnfPackageLocation() + "\"}";
}
 
Example 8
Source File: SearchDao.java    From iBeebo with GNU General Public License v3.0 5 votes vote down vote up
public SearchStatusListBean getStatusList() throws WeiboException {

        String url = WeiBoURLs.STATUSES_SEARCH;

        Map<String, String> map = new HashMap<String, String>();
        map.put("access_token", access_token);
        map.put("count", count);
        map.put("page", page);
        map.put("q", q);

        String jsonData = null;

        jsonData = HttpUtility.getInstance().executeNormalTask(HttpMethod.Get, url, map);

        Gson gson = new Gson();

        SearchStatusListBean value = null;
        try {
            value = gson.fromJson(jsonData, SearchStatusListBean.class);
            List<MessageBean> list = value.getItemList();

            Iterator<MessageBean> iterator = list.iterator();
            while (iterator.hasNext()) {
                MessageBean msg = iterator.next();
                // message is deleted by sina
                if (msg.getUser() == null) {
                    iterator.remove();
                } else {
                    msg.getListViewSpannableString();
                    TimeUtility.dealMills(msg);
                }
            }
        } catch (JsonSyntaxException e) {

            AppLoggerUtils.e(e.getMessage());
        }

        return value;
    }
 
Example 9
Source File: EditTextCustomHolder.java    From dhis2-android-capture-app with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private List<String> getListFromPreference(String key) {
    Gson gson = new Gson();
    String json = binding.customEdittext.getContext().getSharedPreferences(Constants.SHARE_PREFS, MODE_PRIVATE).getString(key, "[]");
    Type type = new TypeToken<List<String>>() {
    }.getType();

    return gson.fromJson(json, type);
}
 
Example 10
Source File: LdapPolicyMgrUserGroupBuilder.java    From ranger with Apache License 2.0 5 votes vote down vote up
private void getUserGroupAuditInfo(UgsyncAuditInfo userInfo) {
	if(LOG.isDebugEnabled()){
		LOG.debug("==> PolicyMgrUserGroupBuilder.getUserGroupAuditInfo()");
	}
	String response = null;
	ClientResponse clientRes = null;
	Gson gson = new GsonBuilder().create();
	String relativeUrl = PM_AUDIT_INFO_URI;

	if(isRangerCookieEnabled){
		response = cookieBasedUploadEntity(userInfo, relativeUrl);
	}
	else {
		try {
			clientRes = ldapUgSyncClient.post(relativeUrl, null, userInfo);
			if (clientRes != null) {
				response = clientRes.getEntity(String.class);
			}
		}
		catch(Throwable t){
			LOG.error("Failed to get response, Error is : ", t);
		}
	}
	if (LOG.isDebugEnabled()) {
		LOG.debug("RESPONSE[" + response + "]");
	}
	gson.fromJson(response, UgsyncAuditInfo.class);

	if(LOG.isDebugEnabled()){
		LOG.debug("AuditInfo Creation successful ");
		LOG.debug("<== LdapPolicyMgrUserGroupBuilder.getUserGroupAuditInfo()");
	}
}
 
Example 11
Source File: TransactionHistoryFragment.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
private void loadFromCache() {
    String jsonFromPref = sharedManager.getTxsCache();
    if (!jsonFromPref.equalsIgnoreCase("")) {
        Gson gson = new Gson();
        Type listType = new TypeToken<Map<String, ArrayList<TransactionItem>>>(){}.getType();
        Map<String, ArrayList<TransactionItem>> addrTxsMap = gson.fromJson(jsonFromPref, listType);
        ArrayList<TransactionItem> txList = addrTxsMap.get(walletManager.getWalletFriendlyAddress());
        if (txList != null) {
            transactionsManager.setTransactionsList(txList);
            initTransactionHistoryRecycler();
        }
    }
}
 
Example 12
Source File: RuntimeTypeAdapterFactoryTest.java    From gson with Apache License 2.0 5 votes vote down vote up
public void testSerializeWrappedNullValue() {
  TypeAdapterFactory billingAdapter = RuntimeTypeAdapterFactory.of(BillingInstrument.class)
      .registerSubtype(CreditCard.class)
      .registerSubtype(BankTransfer.class);    
  Gson gson = new GsonBuilder()
      .registerTypeAdapterFactory(billingAdapter)
      .create();    
  String serialized = gson.toJson(new BillingInstrumentWrapper(null), BillingInstrumentWrapper.class);
  BillingInstrumentWrapper deserialized = gson.fromJson(serialized, BillingInstrumentWrapper.class);
  assertNull(deserialized.instrument);
}
 
Example 13
Source File: ExamPageTeacher.java    From ExamStack with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 学员试卷
 * @param model
 * @param request
 * @param examhistoryId
 * @return
 */
@RequestMapping(value = "/teacher/exam/student-answer-sheet/{histId}", method = RequestMethod.GET)
private String studentAnswerSheetPage(Model model, HttpServletRequest request, @PathVariable int histId) {
	
	ExamHistory history = examService.getUserExamHistListByHistId(histId);
	int examPaperId = history.getExamPaperId();
	
	String strUrl = "http://" + request.getServerName() // 服务器地址
			+ ":" + request.getServerPort() + "/";
	
	ExamPaper examPaper = examPaperService.getExamPaperById(examPaperId);
	StringBuilder sb = new StringBuilder();
	if(examPaper.getContent() != null && !examPaper.getContent().equals("")){
		Gson gson = new Gson();
		String content = examPaper.getContent();
		List<QuestionQueryResult> questionList = gson.fromJson(content, new TypeToken<List<QuestionQueryResult>>(){}.getType());
		
		for(QuestionQueryResult question : questionList){
			QuestionAdapter adapter = new QuestionAdapter(question,strUrl);
			sb.append(adapter.getStringFromXML());
		}
	}
	
	model.addAttribute("htmlStr", sb);
	model.addAttribute("exampaperid", examPaperId);
	model.addAttribute("examHistoryId", history.getHistId());
	model.addAttribute("exampapername", examPaper.getName());
	model.addAttribute("examId", history.getExamId());
	return "student-answer-sheet";
}
 
Example 14
Source File: Utils.java    From datakernel with Apache License 2.0 5 votes vote down vote up
static <T> T fromJson(Gson gson, String json, Type typeOfT) throws ParseException {
	try {
		return gson.fromJson(json, typeOfT);
	} catch (JsonSyntaxException e) {
		throw new ParseException(Utils.class, "Failed to read from json", e);
	}
}
 
Example 15
Source File: QuotePostTest.java    From jumblr with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    Map<String, Object> flat = new HashMap<String, Object>();
    flat.put("type", "quote");
    flat.put("source", source);
    flat.put("text", text);
    flat.put("author", author);
    flat.put("slug", slug);
    flat.put("notes", notes);
    flat.put("note_count", 123);
    Gson gson = new GsonBuilder().registerTypeAdapter(Post.class, new PostDeserializer()).create();
    post = (QuotePost) gson.fromJson(flatSerialize(flat), Post.class);
}
 
Example 16
Source File: GsonUtils.java    From SmartChart with Apache License 2.0 5 votes vote down vote up
public static <T> T parser(String jsonResult, Class<T> clazz) {
    try {
        Gson gson = new GsonBuilder().create();
        return gson.fromJson(jsonResult, clazz);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 17
Source File: ComponentSwitch.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
public ComponentSwitch(ThingUID thing, HaID haID, String configJSON,
        @Nullable ChannelStateUpdateListener channelStateUpdateListener, Gson gson) {
    super(thing, haID, configJSON, gson);
    config = gson.fromJson(configJSON, Config.class);

    // We do not support all HomeAssistant quirks
    if (config.optimistic && StringUtils.isNotBlank(config.state_topic)) {
        throw new UnsupportedOperationException("Component:Switch does not support forced optimistic mode");
    }

    channels.put(switchChannelID,
            new CChannel(this, switchChannelID, new OnOffValue(config.state_on, config.state_off),
                    config.state_topic, config.command_topic, config.name, "", channelStateUpdateListener));
}
 
Example 18
Source File: ConfigPreferences.java    From MuslimMateAndroid with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Function to get weather of the week
 *
 * @return Weather list of week
 */
public static WeatherSave getWeekListWeather(Context context) {
    SharedPreferences sharedPreferences = context.getSharedPreferences
            (MAIN_CONFIG, Context.MODE_PRIVATE);
    Gson gson = new Gson();
    String json = sharedPreferences.getString(WEEK_WETHER, "");
    WeatherSave weathers = gson.fromJson(json, WeatherSave.class);
    return weathers;
}
 
Example 19
Source File: VideoParseJson.java    From BambooPlayer with Apache License 2.0 4 votes vote down vote up
public static VideoDetialData[] parseRead(String json)
{
	Gson gson = new Gson();
	return gson.fromJson(json, VideoDetialData[].class);
}
 
Example 20
Source File: CollectionTest.java    From lsp4j with Eclipse Public License 2.0 4 votes vote down vote up
protected void assertParse(Object expected, String string) {
	Gson gson = createGson();
	Object actual = gson.fromJson(string, expected.getClass());
	Assert.assertEquals(expected, actual);
}