Android项目之JSON解析
JSON
- JSON 是用于存储和传输数据的格式,通常用于服务端向网页传递数据
- JSON英文全称 JavaScript Object Notation(JavaScript 对象表示法),是一种轻量级的用于存储和交换文本信息的语法,被设计用于可读的数据交换,类似 XML,但比 XML 更小、更快,JSON具有自我描述性,更易理解
JSON语法
JSON 的语法基本上可以视为 JavaScript 语法的一个子集,包括以下内容:
- 数据使用名/值对表示
- 使用大括号保存对象,每个名称后面跟着一个 ‘:’(冒号),名/值对使用 ,(逗号)分割
- 使用方括号保存数组,数组值使用 ,(逗号)分割
{
"book": [
{
"id":"01",
"language": "Java",
"edition": "third",
"author": "Herbert Schildt"
},
{
"id":"07",
"language": "C++",
"edition": "second"
"author": "E.Balagurusamy"
}]
}
JSON 支持以下两种数据结构:
- 名/值对集合: 这一数据结构由不同的编程语言支持
- 有序的值列表: 包括数组,列表,向量或序列等等
JSON解析技术
Android中使用Gson框架技术解析JSON
添加GSON
-
通过
jar
包 -
通过
Gradle
添加依赖compile 'com.google.code.gson:gson:2.8.5'
使用GSON
-
创建Gson对象
Gson gson = new Gson();
-
通过创建的Gson对象调用fromJson()方法,返回该json数据对象的Java对象
ShopInfo shopInfo = gson.fromJson(json, ShopInfo.class);
示例代码:
我的JSON文件:
{
"Content_name": "MultiViewVideo",
"BoundingBox_center": [0, 0, 0],
"ViewPointNumbers": 2,
"cameras": [
{
"ViewpointID":0,
"Position": [0, 0, 0],
"Uri": "/storage/emulated/0/Download/3D_Rio_basketball.MP4"
},
{
"ViewpointID":1,
"Position": [1, 1, 1],
"Uri": "/storage/emulated/0/Download/3D_Rio_shark.MP4"
}]
}
对应设计的类:
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
public class ViewPointManager {
@SerializedName("Content_name")
public String contextName;
@SerializedName("BoundingBox_center")
public int[] box_center;
@SerializedName("ViewPointNumbers")
public int viewpointNums;
@SerializedName("cameras")
public ArrayList<Viewpoint> list;
static public class Viewpoint{
@SerializedName("ViewpointID")
public int viewpointID;
@SerializedName("Position")
public int[] position; // 暂时使用int类型,可能用Float类型会更好
@SerializedName("Uri")
public String uri;
}
// TODO:编写搜索与位置对应的URI信息
}
从本地Assets目录下获取JSON文件的字符串
// 读取JSON文件
public String GetJSONString() {
InputStreamReader inputStreamReader;
String MyJSONString=null;
try {
// assets文件夹放在main目录下
inputStreamReader = new InputStreamReader(getAssets().open(
"MultiviewVideo.json"), "UTF-8");
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
while ((MyJSONString = bufferedReader.readLine()) != null) {
stringBuilder.append(MyJSONString);
}
inputStreamReader.close();
bufferedReader.close();
Log.i("TAG", stringBuilder.toString());
MyJSONString = stringBuilder.toString();
} catch (IOException e) {
e.printStackTrace();
}
return MyJSONString;
}
调用GSON解析JSON文件
Gson gson = new Gson();
// 读取Assets中的.json文件
String MyJson = GetJSONString();
// JSON文件解析
ViewPointManager viewPointManager = gson.fromJson(MyJson,ViewPointManager.class);