My Android成長の道(二)——【JSON】

3056 ワード

AndroidクライアントがJSON文字列を受信した場合、解析が必要です.
Android自体はjsonの解析とパッチワークの方法が統合されているので使いやすいです.

import java.util.ArrayList;
import java.util.List;

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

public class ParseJson {
	/**
	 *   JSON   
	 *  :        Object
	 * @param jsontext    
	 * @return   JSONObject
	 */
	public static JSONObject getJson(String jsontext)
	{
		JSONObject object = null;
		try {
			JSONArray entries = new JSONArray(jsontext);
			object =  entries.getJSONObject(0);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return object;
	}
	
	/**
	 *   JSON   
	 *  :     JSONObject
	 * @param jsontext    
	 * @return   JSONObject
	 */
	public static List<JSONObject> getJsons(String jsontext)
	{
		List<JSONObject> objs = new ArrayList<JSONObject>();
		try {
			JSONArray entries = new JSONArray(jsontext);
			for (int i = 0; i < entries.length(); i++) {
				JSONObject object = entries.getJSONObject(i);
				objs.add(object);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return objs;
	}
}

次にテストして、jsonの組み立てを実証するために、次のコードを示します.

public class FActivity extends Activity
{
    private TextView txtmain;
    
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.fmain);
        String s = "";
        
        txtmain = (TextView) findViewById(R.id.txtmain);

        JSONArray array = new JSONArray();
		
        // android       json   ,Person      
	List<Person> persons = new ArrayList<Person>();
	persons.add(new Person("zhuqiang", 24, false));
        //            Person  
        //persons.add(new Person("xiyaqiang", 28, true));
	//persons.add(new Person("sunhaibo", 23, false));
	//persons.add(new Person("meibaocai", 26, false));
	//persons.add(new Person("weiqiang", 29, true));
        for (Person bean : persons) 
	{
		//     JSON  
		JSONObject obj = new JSONObject();
		try 
		{
			obj.put("name", bean.getName());
			obj.put("age", bean.getAge());
			obj.put("marriage", bean.isMarriage());
		} catch (Exception e) {
			e.printStackTrace();
		}
		array.put(obj);
	}

        //       Object
        //  JSONObject ParseJson.getJsons(String jsontext)
        s = ParseJson.getJson(array.toString()).getString("name");

        txtmain.setText(s);

    }
}

一般的にHttpClientと組み合わせて使用されるのは、サーバがHttp方式で返すJSON文字列のクライアントを使用することができるからである.