當前位置: 首頁>>代碼示例>>Java>>正文


Java JsonParser.parse方法代碼示例

本文整理匯總了Java中com.google.gson.JsonParser.parse方法的典型用法代碼示例。如果您正苦於以下問題:Java JsonParser.parse方法的具體用法?Java JsonParser.parse怎麽用?Java JsonParser.parse使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在com.google.gson.JsonParser的用法示例。


在下文中一共展示了JsonParser.parse方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: execute

import com.google.gson.JsonParser; //導入方法依賴的package包/類
/**
 * Pings the server
 * 
 * @source https://www.mkyong.com/java/how-to-send-http-request-getpost-in-java/
 * */
private void execute() throws Throwable {
	//don't execute on debug-mode
	if(this.debugging == true)
		return;
	
	String url = "https://redunda.sobotics.org/status.json";
	URL obj = new URL(url);
	HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

	//add request header
	con.setRequestMethod("POST");
	con.setRequestProperty("User-Agent", UserAgent.getUserAgent());
	
	String parameters = "key="+this.apiKey;
	
	//add version parameter if available
	if (this.version != null)
		parameters = parameters+"&version="+this.version;

	// Send post request
	con.setDoOutput(true);
	DataOutputStream wr = new DataOutputStream(con.getOutputStream());
	wr.writeBytes(parameters);
	wr.flush();
	wr.close();

	BufferedReader in = new BufferedReader(
	        new InputStreamReader(con.getInputStream()));
	String inputLine;
	StringBuffer response = new StringBuffer();

	while ((inputLine = in.readLine()) != null) {
		response.append(inputLine);
	}
	in.close();
	
	String responseString = response.toString();
	
	//http://stackoverflow.com/a/15116323/4687348
	JsonParser jsonParser = new JsonParser();
	JsonObject object = (JsonObject)jsonParser.parse(responseString);
	
	try {
		boolean standbyResponse = object.get("should_standby").getAsBoolean();
		boolean oldValue = PingService.standby.get();
		PingService.standby.set(standbyResponse);
		
		String newLocation = object.get("location").getAsString();
		PingService.location = newLocation;
		
		if (standbyResponse != oldValue) {
			if (this.delegate != null)this.delegate.standbyStatusChanged(standbyResponse);
		}
	} catch (Throwable e) {
		//no apikey or server might be offline; don't change status!
		this.forwardError(e);
		throw e;
	}
}
 
開發者ID:SOBotics,項目名稱:Redunda-lib-java,代碼行數:65,代碼來源:PingService.java

示例2: LoadMovies

import com.google.gson.JsonParser; //導入方法依賴的package包/類
public void LoadMovies(String path) throws FileNotFoundException {
    parser = new JsonParser();
    Object obj = parser.parse(new FileReader(path));

    JsonArray Filme = (JsonArray) obj;

    for (JsonElement j : Filme) {
        JsonObject jsonObject = j.getAsJsonObject();
        FilmeSammlung.Filme.add(
                new Film(
                        jsonObject.get("id").getAsString(),
                        jsonObject.get("name").getAsString(),
                        jsonObject.get("beschreibung").getAsString(),
                        jsonObject.get("dauer").getAsString(),
                        jsonObject.get("altersbegrenzung").getAsString(),
                        jsonObject.get("dreidfaehigkeit").getAsString(),
                        jsonObject.get("sprache").getAsString()
                )
        );

    }
}
 
開發者ID:fabianbaechli,項目名稱:kino_system,代碼行數:23,代碼來源:LoadFromJSON.java

示例3: parseRandomArticle

import com.google.gson.JsonParser; //導入方法依賴的package包/類
/**
 * Finds the random article in the specified JSON data.
 * @return The title of a random Wikipedia article.
 */
public static String parseRandomArticle(String json) {
	// Create a JSON Parser using GSON and parse the root of the JSON data
	JsonParser jParser = new JsonParser();
	JsonElement root = jParser.parse(json);
	
	// Navigate Root -> Query -> Random
	JsonElement jQuery = root.getAsJsonObject().get("query");
	JsonElement jRandom = jQuery.getAsJsonObject().get("random");
	
	// Fetch the random array in the JSON data and just get the first 
	// element.	
	JsonArray randomArray = jRandom.getAsJsonArray();
	JsonObject first = randomArray.get(0).getAsJsonObject();
	return first.get("title").getAsString();
}
 
開發者ID:antverdovsky,項目名稱:Wiki-Degrees,代碼行數:20,代碼來源:DataParse.java

示例4: match

import com.google.gson.JsonParser; //導入方法依賴的package包/類
@Override
public void match(MvcResult result) throws Exception {
    String content = result.getResponse().getContentAsString();

    final JsonParser parser = new JsonParser();
    final JsonElement actual = parser.parse(content);

    if (actual.isJsonPrimitive()) {
        final JsonElement expected = parser.parse(expectedJsonResponse);
        assertThat(actual, is(expected));
    } else {
        try {
            JSONAssert.assertEquals(expectedJsonResponse, content, false);
        } catch (AssertionError e) {
            throw new ComparisonFailure(e.getMessage(), expectedJsonResponse, content);
        }
    }
}
 
開發者ID:tyro,項目名稱:pact-spring-mvc,代碼行數:19,代碼來源:JsonResponseBodyMatcher.java

示例5: downloadModel

import com.google.gson.JsonParser; //導入方法依賴的package包/類
private PlayerItemModel downloadModel(String p_downloadModel_1_)
{
    String s = "http://s.optifine.net/" + p_downloadModel_1_;

    try
    {
        byte[] abyte = HttpUtils.get(s);
        String s1 = new String(abyte, "ASCII");
        JsonParser jsonparser = new JsonParser();
        JsonObject jsonobject = (JsonObject)jsonparser.parse(s1);
        PlayerItemParser playeritemparser = new PlayerItemParser();
        PlayerItemModel playeritemmodel = PlayerItemParser.parseItemModel(jsonobject);
        return playeritemmodel;
    }
    catch (Exception exception)
    {
        Config.warn("Error loading item model " + p_downloadModel_1_ + ": " + exception.getClass().getName() + ": " + exception.getMessage());
        return null;
    }
}
 
開發者ID:SkidJava,項目名稱:BaseClient,代碼行數:21,代碼來源:PlayerConfigurationParser.java

示例6: parseLocation

import com.google.gson.JsonParser; //導入方法依賴的package包/類
public LocationDTO parseLocation(String result){
    JsonParser parser = new JsonParser();
    JsonObject json = (JsonObject) parser.parse(result);

    JsonElement jsonCode = json.get("status");
    String code = jsonCode.getAsString();
    if(! (code.equals("OK"))){
        return null;
    }

    JsonArray jsonArray = json.getAsJsonArray("results");
    JsonElement elm = jsonArray.get(0);
    JsonObject obj = elm.getAsJsonObject();
    JsonObject ob2 = obj.getAsJsonObject("geometry");
    JsonObject obj3 = ob2.getAsJsonObject("location");
    String jsonString = obj3.toString();

    Gson gson = new GsonBuilder().create();
    LocationDTO loc = gson.fromJson(jsonString, LocationDTO.class);

    return loc;
}
 
開發者ID:mezau532,項目名稱:smart_commuter,代碼行數:23,代碼來源:GoogleGeocodeSync.java

示例7: fileDownloadFinished

import com.google.gson.JsonParser; //導入方法依賴的package包/類
public void fileDownloadFinished(String p_fileDownloadFinished_1_, byte[] p_fileDownloadFinished_2_, Throwable p_fileDownloadFinished_3_)
{
    if (p_fileDownloadFinished_2_ != null)
    {
        try
        {
            String s = new String(p_fileDownloadFinished_2_, "ASCII");
            JsonParser jsonparser = new JsonParser();
            JsonElement jsonelement = jsonparser.parse(s);
            PlayerConfigurationParser playerconfigurationparser = new PlayerConfigurationParser(this.player);
            PlayerConfiguration playerconfiguration = playerconfigurationparser.parsePlayerConfiguration(jsonelement);

            if (playerconfiguration != null)
            {
                playerconfiguration.setInitialized(true);
                PlayerConfigurations.setPlayerConfiguration(this.player, playerconfiguration);
            }
        }
        catch (Exception exception)
        {
            Config.dbg("Error parsing configuration: " + p_fileDownloadFinished_1_ + ", " + exception.getClass().getName() + ": " + exception.getMessage());
        }
    }
}
 
開發者ID:SkidJava,項目名稱:BaseClient,代碼行數:25,代碼來源:PlayerConfigurationReceiver.java

示例8: parse

import com.google.gson.JsonParser; //導入方法依賴的package包/類
public GeoJSONObjectDto parse(String geoJson) {
	if (geoJson == null) {
		return null;
	}

	JsonParser parser = new JsonParser();
	JsonElement parsed = parser.parse(geoJson);
	JsonObject jsonObject = parsed.getAsJsonObject();
	String typeString = jsonObject.get("type").getAsString();
	GeoJSONObjectTypeEnum typeEnum = GeoJSONObjectTypeEnum.valueOf(typeString);
	return (GeoJSONObjectDto) gson.fromJson(parsed, typeEnum.getDtoClass());
}
 
開發者ID:mokszr,項目名稱:ultimate-geojson,代碼行數:13,代碼來源:UltimateGeoJSONParser.java

示例9: saveJson

import com.google.gson.JsonParser; //導入方法依賴的package包/類
public synchronized static void saveJson(String jsonContent, File to) {
	try {
		Gson gson = new GsonBuilder().setPrettyPrinting().create();
		JsonParser jp = new JsonParser();
		JsonElement je = jp.parse(jsonContent);
		jsonContent = gson.toJson(je);
		PrintWriter writer = new PrintWriter(to, "UTF-8");
		writer.println(jsonContent);
		writer.close();
	} catch (Exception ex) {
		error("Failed to save json");
	}
}
 
開發者ID:Moudoux,項目名稱:EMC-Installer,代碼行數:14,代碼來源:Utils.java

示例10: MaxwellRecord

import com.google.gson.JsonParser; //導入方法依賴的package包/類
public MaxwellRecord(String changeValue) {
  JsonParser jsonParser = new JsonParser();
  JsonObject value = (JsonObject) jsonParser.parse(changeValue);

  this.dataSource = getPipeLineName();
  this.database = value.get("database").getAsString();
  this.table = value.get("table").getAsString();
  this.produceTime = value.get("ts").getAsLong();
  this.data = value.get("data").getAsJsonObject();

  if (value.has("old") && !value.get("old").isJsonNull()) {
    this.old = value.get("old").getAsJsonObject();
  }

  switch (value.get("type").getAsString()) {
    case "insert":
      type = RowType.INSERT;
      break;

    case "update":
      type = RowType.UPDATE;
      break;

    case "delete":
      type = RowType.DELETE;
      break;
  }
}
 
開發者ID:HashDataInc,項目名稱:bireme,代碼行數:29,代碼來源:MaxwellPipeLine.java

示例11: getChacheFile

import com.google.gson.JsonParser; //導入方法依賴的package包/類
private JsonObject getChacheFile(Plugin plugin){
    File file = new File(plugin.getDataFolder().getPath()+"/truenonpcdata.json");
    if(file.exists()){
        try{
            JsonParser parser = new JsonParser();
            JsonElement jsonElement = parser.parse(new FileReader(file));
            return jsonElement.getAsJsonObject();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }else return null;
}
 
開發者ID:eltrueno,項目名稱:TruenoNPC,代碼行數:14,代碼來源:TruenoNPC_v1_9_r2.java

示例12: readInjectedDependencies

import com.google.gson.JsonParser; //導入方法依賴的package包/類
private void readInjectedDependencies()
{
    File injectedDepFile = new File(getConfigDir(),"injectedDependencies.json");
    if (!injectedDepFile.exists())
    {
        FMLLog.getLogger().log(Level.DEBUG, "File {} not found. No dependencies injected", injectedDepFile.getAbsolutePath());
        return;
    }
    JsonParser parser = new JsonParser();
    JsonElement injectedDeps;
    try
    {
        injectedDeps = parser.parse(new FileReader(injectedDepFile));
        for (JsonElement el : injectedDeps.getAsJsonArray())
        {
            JsonObject jo = el.getAsJsonObject();
            String modId = jo.get("modId").getAsString();
            JsonArray deps = jo.get("deps").getAsJsonArray();
            for (JsonElement dep : deps)
            {
                JsonObject depObj = dep.getAsJsonObject();
                String type = depObj.get("type").getAsString();
                if (type.equals("before")) {
                    injectedBefore.put(modId, VersionParser.parseVersionReference(depObj.get("target").getAsString()));
                } else if (type.equals("after")) {
                    injectedAfter.put(modId, VersionParser.parseVersionReference(depObj.get("target").getAsString()));
                } else {
                    FMLLog.getLogger().log(Level.ERROR, "Invalid dependency type {}", type);
                    throw new RuntimeException("Unable to parse type");
                }
            }
        }
    } catch (Exception e)
    {
        FMLLog.getLogger().log(Level.ERROR, "Unable to parse {} - skipping", injectedDepFile);
        FMLLog.getLogger().throwing(Level.ERROR, e);
        return;
    }
    FMLLog.getLogger().log(Level.DEBUG, "Loaded {} injected dependencies on modIds: {}", injectedBefore.size(), injectedBefore.keySet());
}
 
開發者ID:F1r3w477,項目名稱:CustomWorldGen,代碼行數:41,代碼來源:Loader.java

示例13: getPayload

import com.google.gson.JsonParser; //導入方法依賴的package包/類
@Override
public String [] getPayload (final PayloadType type, final String body) {
	try {
		final JsonParser parser = new JsonParser ();
		final Gson gson = new GsonBuilder ().setPrettyPrinting ()
			.create ();
		final JsonElement element = parser.parse (body);
		return gson.toJson (element)
			.split ("\n");
	}
	catch (final Exception e) {
		fail (JsonFormatTransformerError.class, "Error while JSON Transformation.", e);
	}
	return new String [] {};
}
 
開發者ID:WasiqB,項目名稱:coteafs-services,代碼行數:16,代碼來源:JsonPayloadLogger.java

示例14: GetTranslation

import com.google.gson.JsonParser; //導入方法依賴的package包/類
public static String GetTranslation(String s){
    String res = "";
    JsonParser parse = new JsonParser();
    JsonObject json = (JsonObject) parse.parse(s);
    res = json.get("translation").getAsString();
    return res;
}
 
開發者ID:guozhaotong,項目名稱:FacetExtract,代碼行數:8,代碼來源:ITranToChinese.java

示例15: stringToJSONArray

import com.google.gson.JsonParser; //導入方法依賴的package包/類
public JsonArray stringToJSONArray(String response){
    JsonParser parser = new JsonParser();
    JsonElement tradeElement = parser.parse(response);
    return tradeElement.getAsJsonArray();
}
 
開發者ID:UMM-CSci-3601-S17,項目名稱:digital-display-garden-iteration-4-revolverenguardia-1,代碼行數:6,代碼來源:testUtils.java


注:本文中的com.google.gson.JsonParser.parse方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。