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(){}.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 = new ArrayList();
	public int getTotal() {
		return total;
	}
	public void setTotal(int total) {
		this.total = total;
	}
	public ArrayList getRows() {
		return rows;
	}
	public void setRows(ArrayList 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;
	}
	
}



你可能感兴趣的:(Android,学习)