利用GSON解析JSON数据

jopen 11年前

main.xml如下:

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"            xmlns:tools="http://schemas.android.com/tools"            android:layout_width="match_parent"            android:layout_height="match_parent"            tools:context=".MainActivity" >                    <TextView                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:layout_centerHorizontal="true"                android:layout_marginTop="20dip"                android:textSize="22sp"                android:text="GSON测试" />                                     <Button                 android:id="@+id/button"                android:layout_width="fill_parent"                android:layout_height="wrap_content"                android:layout_marginTop="180dip"                android:text="将复杂JSON转换为JavaBean格式"                />                </RelativeLayout>  
</div> </div>


TestJavaBean如下:

    package com.rbt;        public class TestJavaBean {            public String COUPON_NO;            public String COUPON_NM;            public String COUPON_IMG;            public String COUPON_CP;            public String COUPON_EXPIRE_DATE;            public String COUPON_EXPIRE_START_DM;            public String COUPON_EXPIRE_END_DM;            public String COUPON_grant_FLAG;            public TestJavaBean() {                super();            }            public String getCOUPON_NO() {                return COUPON_NO;            }            public void setCOUPON_NO(String cOUPON_NO) {                COUPON_NO = cOUPON_NO;            }            public String getCOUPON_NM() {                return COUPON_NM;            }            public void setCOUPON_NM(String cOUPON_NM) {                COUPON_NM = cOUPON_NM;            }            public String getCOUPON_IMG() {                return COUPON_IMG;            }            public void setCOUPON_IMG(String cOUPON_IMG) {                COUPON_IMG = cOUPON_IMG;            }            public String getCOUPON_CP() {                return COUPON_CP;            }            public void setCOUPON_CP(String cOUPON_CP) {                COUPON_CP = cOUPON_CP;            }            public String getCOUPON_EXPIRE_DATE() {                return COUPON_EXPIRE_DATE;            }            public void setCOUPON_EXPIRE_DATE(String cOUPON_EXPIRE_DATE) {                COUPON_EXPIRE_DATE = cOUPON_EXPIRE_DATE;            }            public String getCOUPON_EXPIRE_START_DM() {                return COUPON_EXPIRE_START_DM;            }            public void setCOUPON_EXPIRE_START_DM(String cOUPON_EXPIRE_START_DM) {                COUPON_EXPIRE_START_DM = cOUPON_EXPIRE_START_DM;            }            public String getCOUPON_EXPIRE_END_DM() {                return COUPON_EXPIRE_END_DM;            }            public void setCOUPON_EXPIRE_END_DM(String cOUPON_EXPIRE_END_DM) {                COUPON_EXPIRE_END_DM = cOUPON_EXPIRE_END_DM;            }            public String getCOUPON_grant_FLAG() {                return COUPON_grant_FLAG;            }            public void setCOUPON_grant_FLAG(String cOUPON_grant_FLAG) {                COUPON_grant_FLAG = cOUPON_grant_FLAG;            }            @Override            public String toString() {                return "TestJavaBean [COUPON_NO=" + COUPON_NO + ", COUPON_NM="                        + COUPON_NM + ", COUPON_IMG=" + COUPON_IMG + ", COUPON_CP="                        + COUPON_CP + ", COUPON_EXPIRE_DATE=" + COUPON_EXPIRE_DATE                        + ", COUPON_EXPIRE_START_DM=" + COUPON_EXPIRE_START_DM                        + ", COUPON_EXPIRE_END_DM=" + COUPON_EXPIRE_END_DM                        + ", COUPON_grant_FLAG=" + COUPON_grant_FLAG + "]";            }                            }  
</div> </div>


MainActivity如下:

package com.rbt;    import java.io.BufferedReader;    import java.io.InputStream;    import java.io.InputStreamReader;    import java.lang.reflect.Type;    import java.util.ArrayList;    import java.util.HashMap;    import java.util.List;    import java.util.Map;    import org.apache.http.HttpEntity;    import org.apache.http.HttpResponse;    import org.apache.http.client.entity.UrlEncodedFormEntity;    import org.apache.http.client.methods.HttpPost;    import org.apache.http.impl.client.DefaultHttpClient;    import org.apache.http.message.BasicNameValuePair;    import org.apache.http.params.HttpConnectionParams;    import org.apache.http.protocol.HTTP;    import org.json.JSONArray;    import org.json.JSONObject;    import android.app.Activity;    import android.os.Bundle;    import android.view.View;    import android.view.View.OnClickListener;    import android.widget.Button;    import com.google.gson.Gson;    import com.google.gson.reflect.TypeToken;    /**    * Demo描述:    * 利用GSON解析JSON数据--将json数据封装到ArrayList<Object>中    * 注意:    * JavaBean中的每个变量名于每个JSON数据的字段严格对应.    * 比如大小写    *    */    public class MainActivity extends Activity {       private Gson mGson;       private Button mButton;       private String mJSONData;       private ArrayList<TestJavaBean> mTestJavaBeansArrayList;       private String mUrl="your url";        @Override        protected void onCreate(Bundle savedInstanceState) {            super.onCreate(savedInstanceState);            setContentView(R.layout.main);            init();        }        private void init(){            mButton=(Button) findViewById(R.id.button);            mButton.setOnClickListener(new ClickListenerImpl());        }            private class ClickListenerImpl implements OnClickListener {            @Override            public void onClick(View v) {                switch (v.getId()) {                case R.id.button:                    try {                        mJSONData = getJSONData();                        mGson = new Gson();                        JSONObject jsonObject = new JSONObject(mJSONData);                        JSONArray jsonArray = jsonObject.getJSONArray("COUPON_LIST");                        System.out.println("需要转换的JSONArray=" + jsonArray.toString());                        Type listType = new TypeToken<ArrayList<TestJavaBean>>() {}.getType();                        mTestJavaBeansArrayList = mGson.fromJson(jsonArray.toString(), listType);                        System.out.println("linkedList.size()="+ mTestJavaBeansArrayList.size());                        for (int i = 0; i < mTestJavaBeansArrayList.size(); i++) {                            TestJavaBean testJavaBean = mTestJavaBeansArrayList.get(i);                            System.out.println("现在是第" + i + "个数据:" + " "+ testJavaBean.toString());                        }                        } catch (Exception e) {                        }                    break;                default:                    break;                }            }            }                public String getJSONData() {            HttpEntity httpEntity = null;            HttpResponse response = null;            try {                Map<String, String> paramsHashMap = new HashMap<String, String>();                paramsHashMap.put("IF_NO", "IF0002");                paramsHashMap.put("UID", "12345");                HttpPost httpPost = new HttpPost(mUrl);                DefaultHttpClient httpClient = getHttpClient();                List<BasicNameValuePair> postData = new ArrayList<BasicNameValuePair>();                for (Map.Entry<String, String> entry : paramsHashMap.entrySet()) {                    postData.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));                }                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postData,HTTP.UTF_8);                httpPost.setEntity(entity);                response = httpClient.execute(httpPost);                httpEntity = response.getEntity();                    InputStream is = httpEntity.getContent();                StringBuffer sb = new StringBuffer();                BufferedReader br = new BufferedReader(new InputStreamReader(is));                String line = "";                while ((line = br.readLine()) != null) {                    sb.append(line);                }                return sb.toString();            } catch (Exception e) {                }            return null;            }                private DefaultHttpClient getHttpClient() {            DefaultHttpClient httpClient = new DefaultHttpClient();            HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), 8000);            HttpConnectionParams.setSoTimeout(httpClient.getParams(), 10000);            HttpConnectionParams.setTcpNoDelay(httpClient.getParams(), true);            return httpClient;        }    }  
</div> </div>