搜尋此網誌

顯示具有 json 標籤的文章。 顯示所有文章
顯示具有 json 標籤的文章。 顯示所有文章

2016年12月24日 星期六

【Android】What is different optString() and getString() in JSONObject ?

ref:
http://stackoverflow.com/a/13790789

optString() 和 getString()差別?

The difference is that optString returns the empty string ("") if the key you specify doesn't exist. getString on the other hand throws a JSONException. Use getString if it's an error for the data to be missing, or optString if you're not sure if it will be there.
Edit: Full description from the documentation:
Get an optional string associated with a key. It returns an empty string if there is no such key. If the value is not a string and is not null, then it is converted to a string.

如果你指定的key不存在時,

optString()會回傳 ""



getString() 會跳出exception 因為 key為null。

2015年8月20日 星期四

【Android】實作從html讀取JSON 〈2〉

最近想測試從網頁上讀Json並在Android手機上

舊方法:【Java】實作從html讀取JSON (應該是說在Android API 22之後Apache HTTP Client Removal,Http Get /post的方法被捨棄 )

新方法:以HttpURLConnection實作讀取

因為是要顯示在Android 手機上,那種耗時的網路連線、資料整理的動作並不能在main thread中做處理,所以需要額外開一條Thread在background做處理或是以AsyncTask。
在這裡使用AsyncTask來處理相關動作。(更多關於AsyncTask)

較重要的程式碼,如下:

AndroidManifest.xml
須加上
<uses-permission android:name="android.permission.INTERNET" />
允許使用網路
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE">
</uses-permission>
允許檢查網路狀態

FetchTask.java
public class FetchTask extends AsyncTask<String,Void,String> {

    interface OnFetchListener {
        public void OnAirDataFetchFinished();
    }

    private OnFetchListener onFetchListener;

    public void setOnFetchListener(OnFetchListener listener) {
        onFetchListener =listener;
    }



    @Override
    protected String doInBackground(String... params) {
        DataFetcher.getInstance().fetchAirData();
        return  DataFetcher.getInstance().getResult();
    }

    @Override
    protected void onPostExecute(String s) {
        onFetchListener.OnAirDataFetchFinished();
    }
}
DataFetcher.java
public class DataFetcher {
    private StringBuilder airData = new StringBuilder();
    private String path = "http://......";
    private ArrayList<AirSiteObject> mItems;

    private DataFetcher() {

    }

    private static DataFetcher mFetcher;

    public static DataFetcher getInstance() {
        if (null == mFetcher) {
            mFetcher = new DataFetcher();
        }
        return mFetcher;
    }

    public void fetchAirData() {
        HttpURLConnection httpURLConnection = null;
        try {
            URL url = new URL(path);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.connect();
            int status = httpURLConnection.getResponseCode();
            switch (status) {
                case 200:
                case 201:
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8"));
                    String line;
                    while ((line = bufferedReader.readLine()) != null) {
                        airData.append(line + "\n");
                    }
                    bufferedReader.close();

            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            if (httpURLConnection != null) {
                httpURLConnection.disconnect();

            }
        }

    }

    public String getResult() {
        return airData.toString();
    }

    //JSONParser
    public ArrayList<AirSiteObject> GetAirData(String result) {
        mItems =new ArrayList<AirSiteObject>();
        JSONObject obj;
        try {
            JSONArray jsonArray = new JSONArray(result);
            for (int i = 0; i < jsonArray.length(); i++) {
                obj = jsonArray.getJSONObject(i);
                mItems.add(new AirSiteObject(obj));
            }

        } catch (JSONException e) {
            Log.e("MYAPP", "unexpected JSON exception", e);
        }
        return mItems;
    }
}
MainActivity.java
private FetchTask mFetchAirDataTask;
記得要
implements FetchTask.OnFetchListener
onCraete method
mFetchAirDataTask = new FetchTask();mFetchAirDataTask.setOnFetchListener(this);executeTask();

判斷網路是否正常
private void executeTask() {
    if (ToolsHelper.isNetworkAvailable(this)) {
        mFetchAirDataTask.execute();    } else {
        Toast.makeText(this, "未偵測到網路,請確認網路狀況。", Toast.LENGTH_LONG).show();    }
}

實作OnFetchListener介面的OnAirDataFetchFinished method
@Override
    public void OnAirDataFetchFinished() {
        String result = DataFetcher.getInstance().getResult();
        listView.setAdapter(new ViewItemAdapter(this, DataFetcher.getInstance().GetAirData(result)));
        if (DataFetcher.getInstance().GetAirData(result).size() == 0) {
            Toast.makeText(this, "資料讀取失敗,請稍候再重試。", Toast.LENGTH_LONG).show();
        }
    }

2014年10月25日 星期六

【Android】array to json/json to array

private void JSONEncode() throws JSONException {
        JSONArray jsonArray = new JSONArray();
 
        for (int i = 0; i < name.length; i++) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", name[i]);
            jsonObject.put("id", id[i]);
            jsonObject.put("score", score[i]);
            jsonArray.put(jsonObject);
        }
 
        Log.i("JSON String", jsonArray.toString());
        JSONString = jsonArray.toString();
    }
 
    private void JSONDecode() throws JSONException {
        JSONArray jsonArray = new JSONArray(JSONString);
        Log.i("Number of Entries", Integer.toString(jsonArray.length()));
 
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String name = jsonObject.getString("name");
            int id = jsonObject.getInt("id");
            double score = jsonObject.getDouble("score");
            Log.i("Entry", "name: " + name + ", id: " + id + ", score: " + score);
        }
    }
ref:Alan's Development Notes

2013年10月8日 星期二

【Java】實作從html讀取JSON

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.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;


public class JSONfunctions {

        public static JSONObject getJSONfromURL(String url, int method) {
                InputStream is = null;
                String result = "";
                JSONObject jObject = null;

                // http post or get
                try {
                        HttpClient httpclient = new DefaultHttpClient();

                        if (method == Globals.METHOD_GET) {
                                HttpGet httpget = new HttpGet(url);
                                HttpResponse response = httpclient.execute(httpget);
                                HttpEntity entity = response.getEntity();
                                is = entity.getContent();
                        }
                        else if( method == Globals.METHOD_POST) {
                                HttpPost httppost = new HttpPost(url);
                                HttpResponse response = httpclient.execute(httppost);
                                HttpEntity entity = response.getEntity();
                                is = entity.getContent();
                        }
                        

                } catch (Exception e) {
                 System.out.printf("log_tag:Error in http connection " + e.toString());
                }

                // convert response to string
                try {
                        BufferedReader reader = new BufferedReader(new InputStreamReader(
                                        is, "utf-8"), 8);
                        StringBuilder sb = new StringBuilder();
                        String line = null;
                        while ((line = reader.readLine()) != null) {
                                sb.append(line + "\n");
                        }
                        is.close();
                        result = sb.toString();
                        System.out.printf("RESULT: %s", result);
                } catch (Exception e) {
                 System.out.printf("log_tag:Error converting result " + e.toString());
                }

                try {

                        jObject = new JSONObject(result);
                } catch (JSONException e) {
                 System.out.printf("log_tag:Error parsing data " + e.toString());
                }

                return jObject;
        }
}
class Globals {
 public final static int METHOD_GET = 1;
    public final static int METHOD_POST = 2;
}
參考:

  1. http://www.androidbegin.com/tutorial/android-parsing-yql-using-json-tutorial/ 
  2. https://code.google.com/p/cabbiemagnet/source/browse/trunk/CabbieMagnetAndroid/src/com/cabbiemagnet/android/?r=27

【JSON】簡介

JSON(Javascript Object Notation)

  • JSON結構
    • 物件型態(Object):
      • 以{}表示。
    • 陣列型態(Array)
      • 以[]表示。
  • JSON資料
    • "key":value:key和value之間用『:』隔開。
  • JSON value表示法
    • 數字(整數或浮點數)
    • 字串(需加上"",ex:"string")
    • 布林函數(boolean,true或者false)
    • NULL
  • 舉例:

{
  "orderID": 12345,
  "shopperName": "John Smith",
  "shopperEmail": "johnsmith@example.com",
  "contents": [
    {
      "productID": 34,
      "productName": "SuperWidget",
      "quantity": 1
    },
    {
      "productID": 56,
      "productName": "WonderWidget",
      "quantity": 3
    }
  ],
  "orderCompleted": true
}
參考:

  1. http://www.elated.com/articles/json-basics/