2016-08-30 122 views
2

這是我在這裏的第一個問題,我已經試着成爲更明確的:)從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(); 
    } 
} 

回答

1

我重拍根據你的方法,你在找什麼它的幾個途徑之一解析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; 
} 
+0

謝謝你的幫助,但我對'字符串jsonText = readFromUrl錯誤(channerUrl); //從URL讀取文本。我有一個錯誤:'未處理的異常:java.io.IOexception' – PotatoesPower

+0

然後只是用try catch塊包裝語句 – Manny265

+0

更改方法是這樣的:public static boolean checkIfOnline(String channel)throws JSONException,IOException – Seelass

0

我會用自己的方式創造了Methode!

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(); 


     String myString =json.get("onair"); 
return mystring;}