在與服務器交互的時候,咱們每每會使用json字符串,今天的例子是java對象轉化爲字符串,java
代碼以下json
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Persion p1 = new Persion(25, "張三", "男"); //生成兩個Persion對象
Persion p2 = new Persion(35, "李四", "男");
final JSONObject jo1 = new JSONObject();//生成兩個JSONObject對象
final JSONObject jo2 = new JSONObject();
try {
jo1.put("is", p1.getId());// 填充
jo1.put("name", p1.getName());
jo1.put("sex", p1.getSex());
jo2.put("is", p2.getId());
jo2.put("name", p2.getName());
jo2.put("sex", p2.getSex());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
show = (EditText) findViewById(R.id.show);
btn1 = (Button) findViewById(R.id.btn1);
btn1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
show.setText(jo1.toString());
}
});
btn2 = (Button) findViewById(R.id.btn2);
btn2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
JSONArray ja = new JSONArray(); //jsonarray對象
ja.put(jo1);
ja.put(jo2);
show.setText(ja.toString());
}
});
}服務器
源碼獲取地址:http://www.exceptionhelp.com/posts/533post