下面列出了com.google.gson.Gson#fromJson ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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));
}
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;
}
@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;
}
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();
}
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);
}
/**
* 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;
}
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));
}
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;
}
}
@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);
}
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);
}
}
/**
* 学员试卷
* @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";
}
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);
}
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();
}
}
}
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()");
}
}
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);
}
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;
}
@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() + "\"}";
}
/**
* 学员试卷
* @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";
}
protected void assertParse(Object expected, String string) {
Gson gson = createGson();
Object actual = gson.fromJson(string, expected.getClass());
Assert.assertEquals(expected, actual);
}
public static VideoDetialData[] parseRead(String json)
{
Gson gson = new Gson();
return gson.fromJson(json, VideoDetialData[].class);
}