专业游戏门户,分享手游网游单机游戏百科知识攻略!

嗨游网
嗨游网

jsonarray用法,json的4种解析方式

来源:小嗨整编  作者:小嗨  发布时间:2023-02-23 03:50
摘要:jsonarray用法,json的4种解析方式- 1AndroidSDK自带的org.json解析 -1.1解析原理基于文档驱动,需要把全部文件读入到内存中,然后遍历所有数据,根据需要检索想要的数据。1.2相关类JSONObjectJS...

jsonarray用法,json的4种解析方式

--  1 Android SDK自带的org.json解析  --

jsonarray用法,json的4种解析方式

1.1 解析原理

基于文档驱动,需要把全部文件读入到内存中,然后遍历所有数据,根据需要检索想要的数据。

1.2 相关类

JSONObject

JSONArray

JSONTokener

JSONStringer

JSONException

public Object nextValue() throws JSONException {    int c = nextCleanInternal();    switch (c) {        case -1:            throw syntaxError("End of input");        case '{':            return readObject();        case '[':            return readArray();        case '\'':        case '"':            return nextString((char) c);        default:            pos--;            return readLiteral();    }}

1.3 示例代码

public class OrgJsonUtil {    /**     * 生成Json     */    public static void createJson(Context context) {        try {            File file = new File(context.getFilesDir(), "orgjson.json");            //实例化一个JSONObject            JSONObject student = new JSONObject();            //向对象中添加数据            student.put("name", "Musk");            student.put("sex", "男");            student.put("age", 50);            JSONObject course1 = new JSONObject();            course1.put("name", "数学");            course1.put("score", 98.2f);            JSONObject course2 = new JSONObject();            course2.put("name", "语文");            course2.put("score", 99);            //实例化一个JSONArray            JSONArray courses = new JSONArray();            courses.put(0, course1);            courses.put(1, course2);            student.put("courses", courses);            //写数据            FileOutputStream fos = new FileOutputStream(file);            fos.write(student.toString().getBytes());            fos.close();            Log.d("TAG", "createJson: " + student);            Toast.makeText(context, "Json创建成功", Toast.LENGTH_SHORT).show();        } catch (Exception e) {            e.printStackTrace();        }    }    /**     * 解析Json     */    public static void parseJson(Context context) {        try {            //读数据            File file = new File(context.getFilesDir(), "orgjson.json");            FileInputStream fis = new FileInputStream(file);            InputStreamReader isr = new InputStreamReader(fis);            BufferedReader br = new BufferedReader(isr);            String line;            StringBuffer sb = new StringBuffer();            while (null != (line = br.readLine())) {                sb.append(line);            }            fis.close();            isr.close();            br.close();            Student student = new Student();            JSONObject studentJsonObject = new JSONObject(sb.toString());            //获取对象            //使用optString在获取不到对应值的时候会返回空字符串"",而使用getString会异常            String name = studentJsonObject.optString("name", "");            String sex = studentJsonObject.optString("sex", "女");            int age = studentJsonObject.optInt("age", 18);            student.setName(name);            student.setSex(sex);            student.setAge(age);            //获取数组            List<Course> courses = new ArrayList<>();            JSONArray coursesJsonArray = studentJsonObject.optJSONArray("courses");            if (coursesJsonArray != null && coursesJsonArray.length() > 0) {                for (int i = 0; i < coursesJsonArray.length(); i++) {                    JSONObject courseJsonObject = coursesJsonArray.optJSONObject(i);                    Course course = new Course();                    String courseName = courseJsonObject.optString("name", "学科");                    float score = (float) courseJsonObject.optDouble("score", 0);                    course.setName(courseName);                    course.setScore(score);                    courses.add(course);                }            }            student.setCourses(courses);            Log.d("TAG", "parseJson: " + student);            Toast.makeText(context, "Json解析成功", Toast.LENGTH_SHORT).show();        } catch (Exception e) {            e.printStackTrace();        }    }}


本文地址:IT问答频道 https://www.eeeoo.cn/itwenda/903299.html,嗨游网一个专业手游免费下载攻略知识分享平台,本站部分内容来自网络分享,不对内容负责,如有涉及到您的权益,请联系我们删除,谢谢!


IT问答
小编:小嗨整编
相关文章相关阅读
  • json文件怎么加注释?

    json文件怎么加注释?

    添加注释//或者/**/在JSON文件中是不允许的JSON有两种数据结构:● 名称/值对的集合:key:value样式;● 值的有序列表:就是Array;而在JSON的文档中说明只要是不符合上面两种结构的都不被支持,并提示错误。那么JS...

  • json如何格式化

    json如何格式化

    python中可以使用json模块来格式化json数据,使用json.loads()函数解析原始的json数据,并使用json.dumps()函数将解析后的数据格式化为带缩进的字符串即可。在Python中,可以使用json模块来格式化JSO...

  • json是啥

    json是啥

    json是一种轻量级的数据交换格式,具有简洁、易读、跨平台和语言的特点,json数据是通过键值对的方式进行组织,其中键是字符串,值可以是字符串、数值、布尔值、数组、对象或者null,在web开发、数据交换和配置文件等方面得到广泛应用。JSO...

  • php怎么把数组转化成json数据

    php怎么把数组转化成json数据

    php是一种广泛使用的服务器端脚本语言,常用于网站开发、动态网页生成以及web应用程序开发中。在许多应用程序开发中,数据传输是非常重要的一环,而json是一种轻量级的数据交换格式,因其简洁、易用、可扩展的特点而得到广泛应用。在php中,我们...

  • 深入解析JWT(JSON Web Token)的原理及用法

    深入解析JWT(JSON Web Token)的原理及用法

    本篇文章给大家带来了关于jwt的相关知识,其中主要介绍了什么是jwt?jwt的原理以及用法是什么?感兴趣的朋友,下面一起来看一下吧,希望对大家有帮助。JSONWebToken(缩写JWT)是目前最流行的跨域认证解决方案,本文介绍它的原...

  • json有哪些数据格式

    json有哪些数据格式

    json数据格式有对象格式、数组/集合格式两种,json数据格式的特点:1、简洁性,语法非常简洁明了,易于理解和编写;2、可读性,使用文本格式表示数据,易于阅读和调试;3、可扩展性,支持多种数据类型,可以灵活地表示复杂的数据结构;4、平台无...

  • JSON是什么意思?

    JSON是什么意思?

    JSON(JavaScriptObjectNotation)是一种轻量级的数据交换格式,它依赖于JavaScript语言,可以用于在不同平台之间传输数据。JSON有一系列独特的语法和结构,它使用简单的文本格式来表示一个对象。JSON本...

  • jsonp格式是什么意思?

    jsonp格式是什么意思?

    JSONP(JSONwithPadding),是一种使用JavaScript加载并解析具有“padding”的JSON数据的方法,在跨域资源共享(CORS)方案之前就已经存在。JSONP解决了跨域请求存在的安全性问题。换句话说,js...

  • 周排行
  • 月排行
  • 年排行

精彩推荐