JSON解析 Gson解析方式 JSONObject JSONArray

直接上代码

主程序代码:

package com.cc.mygson;


import java.net.Proxy.Type;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;

public class MainActivity extends Activity{
	String json = "{\"total\":100,\"rows\":[{\"key\":\"key1\",\"value\":\"value1\"},{\"key\":\"key2\",\"value\":\"value2\"}]}";
	private Gson gson;    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layotu);
		gson = new Gson();

		findViewById(R.id.btn).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				gsonMyJSONType();
			}
		});
	}

/**
 *基础JSON解析方法
 */
	private void gsonJson() {
		try {
			JSONObject jsonObject = new JSONObject(json);
			int total = jsonObject.getInt("total");
			JSONArray array = jsonObject.getJSONArray("rows");
			for(int i = 0 ;i<array.length();i++){
				String key = array.getJSONObject(i).getString("key");
				String value = array.getJSONObject(i).getString("value");
			}
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}
	/**
	 *一般Gson解析方法
	 */
	private void gsonMyJSON(){
		MyJson myJson = gson.fromJson(json, MyJson.class);
		int total = myJson.getTotal();
	}
	/**
	 * 一般Type  Gson解析方法
	 */
	private void gsonMyJSONType(){
		java.lang.reflect.Type type = 	new TypeToken<MyJson>(){}.getType();
		MyJson myJson = gson.fromJson(json, type);
		int total = myJson.getTotal();
	}
}


MyJson类内容为下:

package com.cc.mygson;

import java.util.ArrayList;

public class MyJson {
	private int total; 
	private ArrayList<Rows> rows = new ArrayList<Rows>();
	public int getTotal() {
		return total;
	}
	public void setTotal(int total) {
		this.total = total;
	}
	public ArrayList<Rows> getRows() {
		return rows;
	}
	public void setRows(ArrayList<Rows> rows) {
		this.rows = rows;
	}

}

Rows类内容为下:

package com.cc.mygson;

public class Rows {
	private String key ;
	private String value ;
	public String getKey() {
		return key;
	}
	public void setKey(String key) {
		this.key = key;
	}
	public String getValue() {
		return value;
	}
	public void setValue(String value) {
		this.value = value;
	}
	
}



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值