日期:2014-05-16 浏览次数:20439 次
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; } }
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); } }