gpt4 book ai didi

java - 从 JSON 中获取值并将其放入 String

转载 作者:行者123 更新时间:2023-11-30 10:39:33 25 4
gpt4 key购买 nike

这是我的第一个问题,我试着说得更明确:)

我想从 JSON 页面获取值:https://api.dailymotion.com/video/x3p6d9r?fields=onair .

我遵循了关于 json 对象 的教程。

但我想获取值 "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();
}
}

最佳答案

我根据你正在寻找的内容重新制作你的方法,这是解析 json 数据的几种方法之一:

 public static boolean checkIfOnline(String channel) throws JSONException, IOException {
String channerUrl = "https://api.dailymotion.com/video/x3p6d9r?fields=onair";

String jsonText = readFromUrl(channerUrl);// reads text from URL

JSONObject json = new JSONObject(jsonText); // You create a json object from your string jsonText
if(json.has("onair")) { // just a simple test to check the node that you need existe
boolean value = json.getBoolean("onair"); // In the url that you gave onair value is boolean type
return value;
}
return false;
}

关于java - 从 JSON 中获取值并将其放入 String,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39231321/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com