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":"三年二班"
}
Android笔记(五十) Android中的JSON数据的更多相关文章
- Android(java)学习笔记208:Android中操作JSON数据(Json和Jsonarray)
1.Json 和 Xml JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式.它基于ECMAScript的一个子集. JSON采用完全独立于语言的 ...
- Android(java)学习笔记151:Android中操作JSON数据(Json和Jsonarray)
1.Json 和 Xml JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式.它基于ECMAScript的一个子集. JSON采用完全独立于语言的 ...
- 截取HTML中的JSON数据并利用GSON进行解析(Android)
截取HTML中的JSON数据并利用GSON进行解析(Android) 前言 最近在做的一个Android项目,需要自行搭建服务器,队友选择买了阿里云的服务器ESC产品,在数据获取上,我们采用了Andr ...
- python3.4学习笔记(二十六) Python 输出json到文件,让json.dumps输出中文 实例代码
python3.4学习笔记(二十六) Python 输出json到文件,让json.dumps输出中文 实例代码 python的json.dumps方法默认会输出成这种格式"\u535a\u ...
- 【Spring学习笔记-MVC-3.1】SpringMVC返回Json数据-方式1-扩展
<Spring学习笔记-MVC>系列文章,讲解返回json数据的文章共有3篇,分别为: [Spring学习笔记-MVC-3]SpringMVC返回Json数据-方式1:http://www ...
- 关于mysql中存储json数据的读取问题
在mysql中存储json数据,字段类型用text,java实体中用String接受. 返回前端时(我这里返回前端的是一个map),为了保证读取出的数据排序错乱问题,定义Map时要用LinkedHas ...
- JMeter 中对于Json数据的处理方法
JMeter中对于Json数据的处理方法 http://eclipsesource.com/blogs/2014/06/12/parsing-json-responses-with-jmeter/ J ...
- java读取url中json文件中的json数据
有时候需要远程从其他接口中获取json数据,如果遇到返回的json数据是一个文件而不直接是数据,那么可以通过以下方法进行读取: /** * 从数据接口获取到数据 * @return * @throws ...
- vue中引入json数据,不用本地请求
1.我的项目结构,需要在Daily.vue中引入daily.js中的json数据 2.把json数据放入一个js文件中,用exports导出,vscode的json格式太严格了,很多数据,调了一个多小 ...
- ASP.NET Core中返回 json 数据首字母大小写问题
ASP.NET Core中返回 json 数据首字母大小写问题 在asp.net core中使用ajax请求动态绑定数据时遇到该问题 后台返回数据字段首字母为定义的大写,返回的数据没有问题 但是在前台 ...
随机推荐
- git - 3.分支
分支介绍 每次提交,Git都把它们串成一条时间线,这条时间线就是一个分支.截止到目前,只有一条时间线, 在Git里,这个分支叫主分支,即master分支. HEAD严格来说不是指向提交,而是指向mas ...
- Js ascii 16进制 url-encode
function fixedEncodeURIComponent (str) { return str.replace(/./g, function(c) { return '%' + c.charC ...
- springboot项目中使用spring-data-Redis对map序列化时报错
错误信息: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String at org.spri ...
- Echartjs axis.getAxesOnZeroOf is not a function
该问题已经解决,下面是解决思路! 问题描述: axis.getAxesOnZeroOf is not a function 使用echart 出现报这句错误,请求解决方案! 问题原因: 我给坐标设置了 ...
- HTTP协议:从原理到流程|乐字节
这次给大家带来的是HTTP协议:从原理到流程的详解 一.HTTP 协议 HTTP 协议(Hypertext Transfer Protocol, 超文本传输协议),是一个客户端请求和回应的 标准协议, ...
- Word 自带公式编写多行公式时在任意位置对齐 -- 含视频教程(10)
1. 方法1:表格法之利用"点"运算符对齐(简单) 以下百度经验是我自己写的,不想放在上边了,移到这里. 2. 方法2:表格法之制表位对齐法(复杂) 未完 ...... 点击访问原 ...
- 跨域和CORS
一 跨域 同源策略(Same origin policy)是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响.可以说Web是构建在同源策略基础之上的 ...
- Python-11-生成器
一.定义 可以理解为一种数据类型,这种数据类型自动实现了迭代器协议(其他数据类型需要调用__iter__方法),所以生成器就是一种迭代器. 二.生成器的两种形式 1. 生成器函数 使用yield代替r ...
- CORS和CSRF
CORS和CSRF 什么是CORS?CORS是一个W3C标准,全称是"跨域资源共享",他允许浏览器向夸源服务器,发出XMLHTTPRequest请求,从而克服了AJAX只能同源使用 ...
- [洛谷P5323][BJOI2019]光线
题目大意:有$n$层玻璃,每层玻璃会让$a\%$的光通过,并把$b\%$的光反射.有一束光从左向右射过,问多少的光可以透过这$n$层玻璃 题解:事实上会发现,可以把连续的几层玻璃合成一层玻璃,但是要注 ...