- //假设现在要创建这样一个json文本
- //{
- //"phone":["12345678","87654321"],//数组
- //"name":"yuanzhifei89",//字符串
- //"age":100,//数值
- //"address":{"country":"china","province":"jiangsu"},//对象
- //"married":false//布尔值
- //}
- try{
- //首先最外层是{},是创建一个对象
- JSONObjectperson=newJSONObject();
- //第一个键phone的值是数组,所以需要创建数组对象
- JSONArrayphone=newJSONArray();
- phone.put("12345678").put("87654321");
- person.put("phone",phone);
- person.put("name","yuanzhifei89");
- person.put("age",100);
- //键address的值是对象,所以又要创建一个对象
- JSONObjectaddress= address.put("country","china");
- address.put("province","jiangsu");
- person.put("address",address);
- person.put("married",false);
- }catch(JSONExceptionex){
- //键为null或使用json不支持的数字格式(NaN,infinities)
- thrownewRuntimeException(ex);
- }