2013-11-03 60 views
0

我有很簡單的JSON格式的數據,它看起來像這樣:我的Android JSON解析器沒有工作,爲什麼?從<a href="http://services.packetizer.com/spotprices/?f=json" rel="nofollow noreferrer">here</a>

{ 
    "date" : "2013-11-01", 
    "gold" : "1317.29", 
    "silver" : "21.90", 
    "platinum" : "1458.00" 
} 

我只需要獲得「黃金」標籤的價值。

我的代碼是:

import java.io.BufferedReader; 
import java.io.InputStream; 
import java.io.InputStreamReader; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.params.BasicHttpParams; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.app.Activity; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.view.Menu; 
import android.widget.TextView; 

public class JsonActivity extends Activity { 

static String jsonUrl = "http://services.packetizer.com/spotprices/?f=json"; 
static String gold = ""; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_json); 
    new MyAsyncTask().execute(); 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.json, menu); 
    return true; 
} 
private class MyAsyncTask extends AsyncTask<String, String, String> { 

    @Override 
    protected String doInBackground(String... arg0) { 
     DefaultHttpClient httpCl = new DefaultHttpClient(new  

    BasicHttpParams()); 
     HttpPost httpP = new HttpPost(jsonUrl); 
     httpP.setHeader("Content-type", "application/json"); 
     InputStream in = null; 
     String result = null; 
     try { 
      HttpResponse response = httpCl.execute(httpP); 
      HttpEntity entity = response.getEntity(); 
      in = entity.getContent(); 
      BufferedReader reader = new BufferedReader(new 
              InputStreamReader(in, "UTF-8"), 8); 
      StringBuilder sbuilder = new StringBuilder(); 

      String line = null; 

      while ((line = reader.readLine()) != null) { 
       sbuilder.append(line + "\n"); 
      } 
      result = sbuilder.toString(); 
     } 
     catch (Exception e) { 
      e.printStackTrace(); 
     } 
     finally { 
      try { 
       if(in != null) 
        in.close(); 
      } 
      catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
     JSONObject jsonObj; 
     try { 
      jsonObj = new JSONObject(result); 
      gold = jsonObj.getString("gold"); 
     } 
     catch (JSONException e) { 
      e.printStackTrace(); 
     } 

     return null; 
    } 

    @Override 
    protected void onPostExecute(String result) { 
     // TODO Auto-generated method stub 
     TextView goldTV = (TextView)findViewById(R.id.goldPrice); 
     goldTV.setText("good price with Json" + gold); 
     super.onPostExecute(result); 
    } 



} 
} 

然而,當我運行它的String gold總是null返回。我無法弄清楚爲什麼?誰能告訴我哪裏出了問題? 感謝

更新 的屏幕截圖說: enter image description here

+0

嘗試打印變量結果並檢查它是否包含任何內容 – Tejas

+0

是否在logcat中看到任何錯誤消息? – Henry

+0

在日誌中找不到任何錯誤cat – dhssa

回答

1

你正在做jsonObj.getString("gold"); ...你現在正在試圖從這個JSON對象的字符串,但在你的JSON,沒有主父對象,例如像: -

{ 
    "Android" : 
      [ 
       { 
        "date" : "2013-11-01", 
        "gold" : "1317.29", 
        "silver" : "21.90", 
        "platinum" : "1458.00" 
       } 
      ] 
} 

這裏Android是您的JSONObject,當你調用getString方法,那麼,你會得到一個字符串變量的黃金價值。通過這兩個教程 去,你就會明白: -

Json Tutorial from Local

Json Tutorial from URL

1

強制與您的代碼

import java.io.BufferedReader; 
import java.io.InputStream; 
import java.io.InputStreamReader; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.params.BasicHttpParams; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.app.Activity; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.view.Menu; 
import android.widget.TextView; 

public class JsonActivity extends Activity { 

static String jsonUrl = "http://services.packetizer.com/spotprices/?f=json"; 
static String gold = ""; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_json); 
    new MyAsyncTask().execute(); 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.json, menu); 
    return true; 
} 
private class MyAsyncTask extends AsyncTask<String, String, String> { 

    @Override 
    protected String doInBackground(String... arg0) { 
     DefaultHttpClient httpCl = new DefaultHttpClient(new  

    BasicHttpParams()); 
     HttpPost httpP = new HttpPost(jsonUrl); 
     httpP.setHeader("Content-type", "application/json"); 
     InputStream in = null; 
     String result = null; 
     try { 
      HttpResponse response = httpCl.execute(httpP); 
      HttpEntity entity = response.getEntity(); 
      in = entity.getContent(); 
      BufferedReader reader = new BufferedReader(new 
              InputStreamReader(in, "UTF-8"), 8); 
      StringBuilder sbuilder = new StringBuilder(); 

      String line = null; 

      while ((line = reader.readLine()) != null) { 
       sbuilder.append(line + "\n"); 
      } 
      result = sbuilder.toString(); 
     } 
     catch (Exception e) { 
      e.printStackTrace(); 
     } 
     finally { 
      try { 
       if(in != null) 
        in.close(); 
      } 
      catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 


     return result; 
    } 

    @Override 
    protected void onPostExecute(String result) { 
     // TODO Auto-generated method stub 

     if(!TextUtils.isEmpty(result)) 
     { 
     JSONObject jsonObj; 
     try { 
      jsonObj = new JSONObject(result); 
      gold = jsonObj.getString("gold"); 
     } 
     catch (JSONException e) { 
      e.printStackTrace(); 
     } 
     TextView goldTV = (TextView)findViewById(R.id.goldPrice); 
     goldTV.setText("good price with Json" + gold); 
     } 
     else 
     { 
      Toast.makeText(this,"response is null",Toast.LENGTH_LONG); 
     } 
     super.onPostExecute(result); 
    } 



} 
} 
+0

你會得到結果嗎?請記錄結果.. – Hardik

1

檢查替換此代碼,如果你jsonObj爲空或不是,如果它是空的也許你應該使用類似這樣的東西:

JSONArray jsonArray; 
JSONObject parent; 
    try { 
     jsonArray = new JSONArray(result); 
     parent = jsonArray.getJsonObject("ParentObject"); 
     gold = parent.getString("gold"); 
    } 
    catch (JSONException e) { 
     e.printStackTrace(); 
    } 
+0

getJSONObject(int)獲取和整數作爲參數?有沒有其他的選擇? – dhssa

+0

我不這麼認爲,但你不能迭代你的數組與foreach或類似的迭代? –

相關問題