Android JSON库是Android操作系统中内置的一个JSON解析库,可以方便地将JSON数据转为Java对象或将Java对象转为JSON数据,并且支持各种类型的数据。
Android JSON库提供了两种不同的API:JSON对象API和JSON流API。JSON对象API使用对象的方式来解析和创建JSON数据,而JSON流API使用流的方式来解析和创建JSON数据。
下面是JSON对象API的示例:
// 创建一个JSON对象 JSONObject jsonObject = new JSONObject(); // 向JSON对象中添加属性 jsonObject.put("name","张三"); jsonObject.put("age",25); jsonObject.put("married",false); // 将JSON对象转为JSON字符串 String jsonString = jsonObject.toString(); // 将JSON字符串转为JSON对象 JSONObject newJsonObject = new JSONObject(jsonString); // 获取JSON对象中的属性值 String name = newJsonObject.getString("name"); int age = newJsonObject.getInt("age"); boolean isMarried = newJsonObject.getBoolean("married");
下面是JSON流API的示例:
// 创建一个JSON流 ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); JsonWriter jsonWriter = new JsonWriter(new OutputStreamWriter(outputStream,"UTF-8")); // 开始写JSON数据 jsonWriter.beginobject(); // 开始一个JSON对象 jsonWriter.name("name").value("张三"); // 添加属性 jsonWriter.name("age").value(25); // 添加属性 jsonWriter.name("married").value(false); // 添加属性 jsonWriter.endobject(); // 结束JSON对象 // 将JSON流转为JSON字符串 String jsonString = outputStream.toString("UTF-8"); outputStream.close(); // 将JSON字符串转为JSON流 ByteArrayInputStream inputStream = new ByteArrayInputStream(jsonString.getBytes("UTF-8")); JsonReader jsonReader = new JsonReader(new InputStreamReader(inputStream,"UTF-8")); // 开始读JSON数据 jsonReader.beginobject(); // 开始一个JSON对象 String name = ""; int age = 0; boolean isMarried = false; while(jsonReader.hasNext()){ // 遍历JSON对象 String key = jsonReader.nextName(); // 获取属性名 if("name".equals(key)){ name = jsonReader.nextString(); // 获取属性值 } else if("age".equals(key)){ age = jsonReader.nextInt(); // 获取属性值 } else if("married".equals(key)){ isMarried = jsonReader.nextBoolean(); // 获取属性值 } else { jsonReader.skipValue(); // 跳过未知属性 } } jsonReader.endobject(); // 结束JSON对象
以上是Android JSON库的基本用法示例,请根据实际需求灵活运用。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。