在与服务器交互的时候,我们往往会使用json字符串,今天的例子是java对象转化为字符串,
代码如下
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/533