2017-10-06 113 views
0

我正在處理隨機報價應用程序,我需要通過http連接解析ajson文件。我成功地建立了連接;並獲取JSON數據,但是當我嘗試解析它時,似乎我得到的鍵,值或對象沒有正確映射。或者,也許我沒有使用正確的代碼。任何幫助讚賞。由於無法正確分析json文件

package com.example.george.radonquote; 

import android.os.AsyncTask; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.support.v7.widget.Toolbar; 
import android.util.Log; 
import android.view.View; 
import android.widget.ImageView; 
import android.widget.TextView; 
import android.widget.Toast; 

import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 
import org.w3c.dom.Text; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.net.HttpURLConnection; 
import java.net.MalformedURLException; 
import java.net.URL; 

public class MainActivity extends AppCompatActivity { 

    Toolbar myToolbar; 
    String randQuote; 
    String author; 
    TextView quoteTextView; 
    ImageView bgImageView; 
    ImageView nextImageView; 
    String url = "http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&_jsonp=mycallback"; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     //setting the ActionBar for the activity 
     myToolbar = (Toolbar) findViewById(R.id.my_toolbar); 
     setSupportActionBar(myToolbar); 

     quoteTextView = (TextView) findViewById(R.id.quote_text); 
     nextImageView = (ImageView) findViewById(R.id.next_quote); 

     /*onclick listener for next quote*/ 
     nextImageView.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       FetchQuote fetchQuote = new FetchQuote(); 
       fetchQuote.execute(); 
      } 
     }); 
    } 

    /* 
    * async class to get random quote in background 
    */ 
    class FetchQuote extends AsyncTask<Void, Void, Void> { 
     String quote = ""; 
     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      Toast.makeText(MainActivity.this,"Fetching Quote!",Toast.LENGTH_LONG).show(); 
     } 

     /* 
     * making connection and parsing json data 
     */ 
     @Override 
     protected Void doInBackground(Void... voids) { 
      try { 
       URL uri = new URL(url); 
       HttpURLConnection urlConnection = (HttpURLConnection) uri.openConnection(); 
       InputStream inputStream = urlConnection.getInputStream(); 
       BufferedReader bf = new BufferedReader(new InputStreamReader(inputStream)); 
       String line = ""; 
       while(line != null) { 
        Log.v("line: ",line); 
        line = bf.readLine(); 
        quote += line; 
       } 
      } 
      catch (MalformedURLException ex) { 
       ex.printStackTrace(); 
      } 
      catch (IOException ex) { 
       ex.printStackTrace(); 
      } 

      try { 
       JSONArray ja = new JSONArray(quote); 
       JSONObject jo = (JSONObject) ja.get(0); 
       randQuote = jo.get("content").toString().replaceAll("\\<[^>]*>",""); 
       author = jo.get("title").toString(); 
       Log.v("QUOTE", randQuote+" "+author); 
      } 
      catch (JSONException ex){ 
       ex.printStackTrace(); 
      } 
      return null; 
     } 

     @Override 
     protected void onPostExecute(Void aVoid) { 
//   Log.v("Post Exec", randQuote); 
      quoteTextView.setText(randQuote); 

     } 
    } 
} 

Output of Service- Parsed

Output of Service- Raw

+0

我們怎麼映射什麼是錯的,你還沒有發佈的響應和你期待什麼映射? –

+0

你得到的迴應不是有效的json。這是開始'/ **/mycallback('。 –

+0

如果我可以得到一個字符串的回調,那麼我可以解析它! – miatech

回答

-1

使用JSOUP庫,並按照給定的代碼

String content; 
content = Jsoup.parse(content).text(); 
+0

我試過,但android studio無法識別類 – miatech

+0

你必須添加jar文件或者可以使用gradle import。在給定網站上下載availabel https://jsoup.org/download或者編譯'org.jsoup:jsoup:1.9.1' –

+0

這不是一個不正確的解決方案,而是一種替代解決方案。 –

0

你沒有得到從URL一個有效的JSON。首先糾正你的字符串,然後解析json。嘗試下面的代碼。這只是一個臨時解決方案。

try { 
       String requiredString = quote.substring(quote.indexOf("(") + 1, quote.indexOf(")")); 
       JSONArray ja = new JSONArray(requiredString); 
       JSONObject jo = (JSONObject) ja.get(0); 
       randQuote = jo.get("content").toString().replaceAll("\\<[^>]*>",""); 
       author = jo.get("title").toString(); 
       Log.v("QUOTE", randQuote+" "+author); 
      } 
0

問題是url中的_jsonp=mycallback參數。使用此參數會導致格式錯誤的JSON返回給您。

正如您在the documentation中看到的,JSONP參數在JavaScript中用於執行回調。

由於您在Android應用程序中使用Java,因此不需要指定回調。

所有你需要做的就是修改URL,這樣它沒有定義的回調:

String url = "http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1"; 

然後,響應將是有效的格式化JSON,例如:

[ 
    { 
     "ID":1572, 
     "title":"Si Scott", 
     "content":"<p>I really like looking at design and thinking: that attention to detail must have taken absolutely ages.<\/p>\n", 
     "link":"https:\/\/quotesondesign.com\/si-scott\/", 
     "custom_meta":{ 
     "Source":"<a href=\"http:\/\/www.formatmag.com\/art\/si-scott\/\">article<\/a>" 
     } 
    } 
] 

然後,你現有的代碼應該工作。我只是測試它,它記錄了正確的響應:

10-06 12:35:52.522 4606-4624/com.example.ex V/QUOTE: Graphic designers find themselves in a role of visual dishwashers for the Information Architects&#8217; chefs. 
                   Gunnar Swanson