Android笔记(五十) Android中的JSON数据

JSON是什么:

JSON是轻量级的文本数据交换格式

JSON独立于语言和平台

JSON具有自我描述性,更容易理解

JSON语法:

数据在名称/值对中

数据由逗号分割

大括号表示对象

中括号表示数组

JSON使用:

MainActivity.java

package cn.lixyz.jsontest.activity;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import cn.lixyz.jsontest.R;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    public void clickButton(View v) {
        switch (v.getId()) {
        case R.id.bt_readjson:
            readJson();
            break;
        case R.id.bt_writejson:
            writeJson();
            break;
        }
    }

    // 往sdcard中写入文件
    private void writeJson() {

        // 创建一个json对象
        JSONObject root = new JSONObject();
        try {
            // 使用put(kay,value)插入元素
            root.put("class", "三年二班");
            // 常见若干对象,用以加入数组
            JSONObject student1 = new JSONObject();
            student1.put("id", 1);
            student1.put("name", "张三");
            student1.put("age", 10);
            JSONObject student2 = new JSONObject();
            student2.put("id", 2);
            student2.put("name", "李四");
            student2.put("age", 11);
            JSONObject student3 = new JSONObject();
            student3.put("id", 3);
            student3.put("name", "王五");
            student3.put("age", 13);
            JSONObject student4 = new JSONObject();
            student4.put("id", 4);
            student4.put("name", "赵六");
            student4.put("age", 14);
            JSONObject student5 = new JSONObject();
            student5.put("id", 5);
            student5.put("name", "孙七");
            student5.put("age", 15);
            JSONObject student6 = new JSONObject();
            student6.put("id", 6);
            student6.put("name", "刘八");
            student6.put("age", 16);
            // 创建一个json数组
            JSONArray array = new JSONArray();
            // 将之前创建的json对象添加进来
            array.put(student1);
            array.put(student2);
            array.put(student3);
            array.put(student4);
            array.put(student5);
            array.put(student6);

            // 将json数组添加
            root.put("student", array);
            Log.d("TTTT", array.toString());
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        String packageName = this.getPackageName();
        String jsonFileName = "json.json";
        String sdCardPath = Environment.getExternalStorageDirectory().toString();

        File sdCardPackagePath = new File(sdCardPath + "/" + packageName);
        if (!sdCardPackagePath.exists()) {
            if (sdCardPackagePath.mkdir()) {
                Log.d("TTTT", "创建目录成功");
            } else {
                Log.d("TTTT", "创建目录不成功");

            }

        }

        File jsonFile = new File(sdCardPackagePath + "/" + jsonFileName);
        if (!jsonFile.exists()) {
            try {
                if (jsonFile.createNewFile()) {
                    Log.d("TTTT", "创建文件成功");
                } else {
                    Log.d("TTTT", "创建文件失败");

                }

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        try {
            // 将json数据写入文件
            FileWriter fileWriter = new FileWriter(jsonFile);
            fileWriter.write(root.toString());
            fileWriter.flush();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    // 读取assets目录中的json文件
    private void readJson() {
        try {
            // 读取assets目录下的json文件
            InputStreamReader isr = new InputStreamReader(getAssets().open("test.json"), "UTF-8");
            BufferedReader br = new BufferedReader(isr);
            String line;
            StringBuilder builder = new StringBuilder();
            while ((line = br.readLine()) != null) {
                builder.append(line);
            }
            br.close();
            // 获取到json文件中的对象
            JSONObject root = new JSONObject(builder.toString());
            // 使用getString(key)方式获取value
            Log.d("TTTT", "class=" + root.getString("class"));
            // 获取json数组
            JSONArray array = root.getJSONArray("student");
            for (int i = 0; i < array.length(); i++) {
                JSONObject student = array.getJSONObject(i);
                Log.d("TTTT", "id=" + student.getInt("id") + ",name=" + student.getString("name") + ",age="
                        + student.getInt("age"));
            }
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="cn.lixyz.jsontest.activity.MainActivity" >

    <Button
        android:id="@+id/bt_writejson"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="clickButton"
        android:text="@string/writejson" />

    <Button
        android:id="@+id/bt_readjson"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="clickButton"
        android:text="@string/readjson" />

</LinearLayout>

/assets/test.json

{
    "student":[
        {"id":1,"name":"张三","age":10},
        {"id":2,"name":"李四","age":11},
        {"id":3,"name":"王五","age":12},
        {"id":4,"name":"赵六","age":13},
        {"id":5,"name":"孙七","age":14},
        {"id":6,"name":"刘八","age":15},
    ],
    "class":"三年二班"
}
时间: 2024-08-06 07:55:41

Android笔记(五十) Android中的JSON数据的相关文章

Android笔记(五):Android中的Radio

原文地址:http://irving-wei.iteye.com/blog/1076097 上篇介绍了CheckBox,这节,将接触到的是RadioGroup和RadioButton. 它们的关系是:一个RadioGroup对应多个RadioButton,而一个RadioGroup中的RadioButton只能同时有一个被选中,它的选中值就是该RadioGroup的选中值. 这一节的代码运行效果图如下所示: 具体的代码编写过程如下: 首先在strings.xml中添加本程序所要用到的字符串: X

android中对json数据的解析,并在listview中实际运用

android中对json数据的解析,并在listview中现实,下面是数据{"ziparea": "410100.0", "enddate": "2015-04-03 00:00:00", "ecertarea": "\u9053\u8def\u8d27\u7269\u8fd0\u8f93\u9a7e\u9a76\u5458", "ecertstate": &quo

Android中解析Json数据

在开发中经常会遇到解析json的问题 在这里总结几种解析的方式: 方式一: json数据: private String jsonData = "[{\"name\":\"Michael\",\"age\":20},{\"name\":\"Mike\",\"age\":21}]"; 解析jsonData的方法 try { //如果需要解析Json数据,首先要生成一个J

【Spring学习笔记-MVC-3.1】SpringMVC返回Json数据-方式1-扩展

<Spring学习笔记-MVC>系列文章,讲解返回json数据的文章共有3篇,分别为: [Spring学习笔记-MVC-3]SpringMVC返回Json数据-方式1:http://www.cnblogs.com/ssslinppp/p/4528892.html [Spring学习笔记-MVC-4]返回Json数据-方式2:http://www.cnblogs.com/ssslinppp/p/4530002.html [Spring学习笔记-MVC-3.1]SpringMVC返回Json数据-

ASP.NET MVC 4 中的JSON数据交互

前台Ajax请求很多时候需要从后台获取JSON格式数据,一般有以下方式: 拼接字符串 return Content("{\"id\":\"1\",\"name\":\"A\"}"); 为了严格符合Json数据格式,对双引号进行了转义. 使用JavaScriptSerialize.Serialize()方法将对象序列化为JSON格式的字符串 MSDN 例如我们有一个匿名对象: var tempObj=new

在mvc4.0中使用json数据

今天接触了mvc4.0项目,View中需要获取从Control传来的json数据.过程记录如下: 在 MVC 返回的ActionResult中,为我们提供了JSONResult(继承至ActionResult)对象,我们可以直接用他来返回JSON对象给View处理 将自定义的Model 实例传给Json方法,它会自动根据我们Model 的属性,遍历属性后生成JSON对象,返回View.然后就可以在前端使用JQ对JSON数据进行处理了 Control中的代码: public JsonResult

JMeter中对于Json数据的处理方法

http://eclipsesource.com/blogs/2014/06/12/parsing-json-responses-with-jmeter/ Json作为一种数据交换格式在网络开发,特别是Ajax与Restful架构中应用的越来越广泛.而Apache的JMeter也是较受欢迎的压力测试工具之一,但是它本身没有提供对于Json数据的响应处理.本文中假设需要从HTTP的响应头中返回的Json格式的数据流中抽取某些特定的数据,数据格式如下: { "name":"Sim

大数据学习笔记6&#183;社会计算中的大数据(4)

上一篇介绍了LifeSpec项目,这个项目是关于用户理解和用户画像的.这篇是社会计算部分的最后一篇,关于用户连接和图隐私. 用户连接与隐私保护 用户连接与隐私保护有很强的相关性. 上图中,左边有两个网络.对于用户连接,我们的目标是映射这两个网络和连接这些网络中的用户节点.然后,我们就能产生一个更大的网络.这样,用户就能够被连接在一起,我们就可以知道跨网络的用户信息. 但是,如果从隐私的角度来看这个问题,把第一个图看成一个匿名化处理后的图,称其为目标图:把第二张图看成辅助图或者攻击者可获得的信息.

在SQL 中生成JSON数据

这段时间接手一个数据操作记录的功能,刚拿到手上的时候打算用EF做,后来经过仔细考虑最后还是觉定放弃,最后思考再三决定: 1.以模块为单位分表.列固定(其实可以所有的操作记录都放到同一个表,但是考虑到数据量大的时候查询性能的问题还是分表吧)列:主键ID.引用记录主键ID.操作时间.操作类型.详细信息(里面存储的就是序列化后的值) 2.在客服端解析保存的序列化的值 但是用xml还是用json呢,这有是一个问题,显然用xml在存储过程正很容易就能生成了:SELECT * FROM TABLE FOR 

vue中引入json数据,不用本地请求

1.我的项目结构,需要在Daily.vue中引入daily.js中的json数据 2.把json数据放入一个js文件中,用exports导出,vscode的json格式太严格了,很多数据,调了一个多小时的格式................. 例如:daily.js module.exports = { 'tmbTmbsContent': [[ {'label': '123'} ]], } 2.在Daily.vue文件中引入 import Daily from '@/assets/data/da