這是我在這裏的第一個問題,我已經試着成爲更明確的:)從JSON獲得價值,並把它放在字符串
我希望得到從JSON
頁值:https://api.dailymotion.com/video/x3p6d9r?fields=onair。
我有關於json object
的教程。
但我想要得到的值爲"onair"
,並把它放在String
中以便使用IF STRING == "XX"
。
這是我的代碼:
public class notification extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification);
detectonline();
}
public void detectonline(){
/*
if (xx == "false") {
Do something is live is off
}
else{
Do something is live is on
}
*/
}
public static boolean checkIfOnline(String channel) throws IOException {
String channerUrl = "https://api.dailymotion.com/video/x3p6d9r?fields=onair";
String jsonText = readFromUrl(channerUrl);// reads text from URL
JsonParser parser = new JsonParser();
JsonObject json = parser.parse(jsonText).getAsJsonObject();
return !json.get("onair").isJsonNull();
}
private static String readFromUrl(String url) throws IOException {
URL page = new URL(url);
StringBuilder sb = new StringBuilder();
Scanner scanner = null;
try{
//scanner = new Scanner(page.openStream(), StandardCharsets.UTF_8.name());
scanner = new Scanner(page.openStream());
while (scanner.hasNextLine()){
sb.append(scanner.nextLine());
}
}finally{
if (scanner!=null)
scanner.close();
}
return sb.toString();
}
}
謝謝你的幫助,但我對'字符串jsonText = readFromUrl錯誤(channerUrl); //從URL讀取文本。我有一個錯誤:'未處理的異常:java.io.IOexception' – PotatoesPower
然後只是用try catch塊包裝語句 – Manny265
更改方法是這樣的:public static boolean checkIfOnline(String channel)throws JSONException,IOException – Seelass