Android(安卓)JSON
16lz
2021-01-26
- JSON是什么
- JSON有哪两种结构
- 如何解析JSONObject
如何解析JSONArray
JSON是什么
json(Javascript Object Notation)是一种用于数据交换的文本格式。2001年由Douglas Crockford提出,目的是取代繁琐笨重的XML格式。
JSON的两种结构
JSON有两种数据结构:
单条JSON数据,Android中称之为JSONObject.
多条JSON组合,Android中称之为JSONArray.
如何解析JSONObject
在工程目录”src/main/java”下创建并解析demo.json:
{ "sex": "male", "name": "John", "is_student": true, "age": 22}
public class JSONObjectSample { public static void main(String[] args) throws IOException { File file = new File("src/main/java/demo.json"); String content = FileUtils.readFileToString(file); //对基本类型的解析 JSONObject obj = new JSONObject(content); System.out.println("name:" + obj.getString("name")); System.out.println("sex:" + obj.getString("sex")); System.out.println("age" + obj.getInt("age")); System.out.println("is_student" + obj.getBoolean("is_student")); } }
如何解析JSONArray
{ "hobbies": [ "hiking", "swimming" ], "sex": "male", "name": "John", "is_student": true, "age": 22}
public class JSONObjectSample { public static void main(String[] args) throws IOException { File file = new File("src/main/java/demo.json"); String content = FileUtils.readFileToString(file); //对基本类型的解析 JSONObject obj = new JSONObject(content); System.out.println("name:" + obj.getString("name")); System.out.println("sex:" + obj.getString("sex")); System.out.println("age" + obj.getInt("age")); System.out.println("is_student" + obj.getBoolean("is_student")); //对数组的解析 JSONArray hobbies = obj.getJSONArray("hobbies"); System.out.println("hobbies:"); for (int i = 0; i < hobbies.length(); i++) { String s = (String) hobbies.get(i); System.out.println(s); } }}
更多相关文章
- Android(安卓)Multimedia框架总结(二十七)MediaCodec回顾
- Android设置输入法
- Android(安卓)Support Annotations 使用详解
- Java bit, byte, 基本数据类型
- android AndroidManifest.xml文件解析
- Android智能POS应用开发学习清单
- JS 判断浏览器客户端类型(ipad,iphone,android)
- Android工程的目录结构详解
- 隐式Intent解析