JSON
莫属JSON
& 解析方式(Gson
、AS
自带org.json
、Jackson
),希望你们会喜欢同样 作为主流的数据交换格式
XML
,有兴趣的读者请看文章:XML简介 & 解析方式(DOM、SAX、PULL)
JSON
值 的形式 存在// JSON实例
{"skill":{
"web":[
{
"name":"html",
"year":"5"
},
{
"name":"ht",
"year":"4"
}],
"database":[
{
"name":"h",
"year":"2"
}]
`}}
JSON
值的内容形式可以是:”名称 - 值“对、数组 或 对象,下面将详细说明类似于
XML
的DOM
解析方式
// 创建需解析的JSON数据:student.json
// 将该文件放入到本地assets文件夹里
{
"student":[
{"id":1,"name":"小明","sex":"男","age":18,"height":175},
{"id":2,"name":"小红","sex":"女","age":19,"height":165},
{"id":3,"name":"小强","sex":"男","age":20,"height":185}
],
"cat":"it"
}
// 具体解析
import android.os.Bundle;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EntityStudent student = new EntityStudent();
try {
//从assets获取json文件
InputStreamReader isr = new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream("assets/" + "student.json"));
//字节流转字符流
BufferedReader bfr = new BufferedReader(isr);
String line ;
StringBuilder stringBuilder = new StringBuilder();
while ((line = bfr.readLine())!=null){
stringBuilder.append(line);
}//将JSON数据转化为字符串
JSONObject root = new JSONObject(stringBuilder.toString());
//根据键名获取键值信息
System.out.println("root:"+root.getString("cat"));
JSONArray array = root.getJSONArray("student");
for (int i = 0;i < array.length();i++)
{
JSONObject stud = array.getJSONObject(i);
System.out.println("------------------");
System.out.print("id="+stud.getInt("id")+ ","));
System.out.print("name="+stud.getString("name")+ ","));
System.out.print("sex="+stud.getString("sex")+ ","));
System.out.print("age="+stud.getInt("age")+ ","));
System.out.println("height="+stud.getInt("height")+ ","));
bfr.close();
isr.close();
is.close();//依次关闭流
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
JSON
数据的JavaBean
类,即可通过简单操作解析出所需数据步骤1:创建一个与JSON数据对应的JavaBean类(用作存储需要解析的数据)Gson
解析的关键 = 根据JSON
数据 写出一个对应的JavaBean
,规则是:
下面用2个例子说明 如何通过JSON
文档创建JavaBean
类
/**
* 简单转换
*/
// JSON数据1
String json = "{\"id\":1,\"name\":\"小明\",\"sex\":\"男\",\"age\":18,\"height\":175}";
// 对应的JavaBean类
public class EntityStudent {
private int id;
private String name;
private String sex;
private int age;
private int height;
public void setId(int id){
this.id = id;
}
public void setName(String name){
this.name = name;
}
public void setSex(String sex){
this.sex = sex;
}
public void setAge(int age){
this.age = age;
}
public void setHeight(int height){
this.height = height;
}
public int getId(){
return id;
}
public String getName(){
return name;
}
public String getSex(){
return sex;
}
public int getAge(){
return age;
}
public int getHeight(){
return height;
}
public void show(){
System.out.print("id=" + id + ",");
System.out.print("name=" + name+",");
System.out.print("sex=" + sex+",");
System.out.print("age=" + age+",");
System.out.println("height=" + height + ",");
}
}
/**
* 复杂转换
*/
// JSON数据2(具备嵌套)
{"translation":["车"],
"basic":
{
"phonetic":"kɑː",
"explains":["n. 汽车;车厢","n. (Car)人名;(土)贾尔;(法、西)卡尔;(塞)察尔"]},
"query":"car",
"errorCode":0,
"web":[{"value":["汽车","车子","小汽车"],"key":"Car"},
{"value":["概念车","概念车","概念汽车"],"key":"concept car"},
{"value":["碰碰车","碰撞用汽车","碰碰汽车"],"key":"bumper car"}]
}
// 对应的复杂的JSON数据对应的JavaBean类
public class student {
public String[] translation; //["车"]数组
public basic basic; //basic对象里面嵌套着对象,创建一个basic内部类对象
public static class basic{ //建立内部类
public String phonetic;
public String[] explains;
}
public String query;
public int errorCode;
public List web; //web是一个对象数组,创建一个web内部类对象
public static class wb{
public String[] value;
public String key;
}
public void show(){
//输出数组
for (int i = 0;i
若觉得转换过于复杂,请直接使用工具:JSON字符串 转 Java实体类
步骤2:导入GSON库
在Android Gradle
导入依赖
dependencies {
compile 'com.google.code.gson:gson:2.3.1'
}
步骤3:使用Gson进行解析
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 1. 创建Gson对象
Gson gson = new Gson();
// 2. 创建JavaBean类的对象
Student student = new EntityStudent();
// 3. 使用Gson解析:将JSON数据转为单个类实体
String json = "{\"id\":1,\"name\":\"小明\",\"sex\":\"男\",\"age\":18,\"height\":175}";
student = gson.fromJson(json,Student.class);
// 解析:JavaBean对象 = gson.fromJson(son,javaBean类类名.class);
// 4. 调用student方法展示解析的数据
student.show();
// 5. 将Java集合转换为json
String json2 = gson.toJson(List);
System.out.println(json2);
}
}
GSON
,先创建1个对应于JSON
数据的JavaBean
类,再通过简单操作即可解析Gson
解析不同的是:GSON
可按需解析,即创建的JavaBean
类不一定完全涵盖所要解析的JSON
数据,按需创建属性;但Jackson
解析对应的JavaBean
必须把Json
数据里面的所有key
都有所对应,即必须把JSON
内的数据所有解析出来,无法按需解析但Jackson的解析速度、效率都 高于 GSON
步骤1:建立Json
数据对应的javaBean(规则同GSON)
// 创建需解析的JSON数据:student.json
// 将该文件放入到本地assets文件夹里
{"student":
[
{"id":1,"name":"小明","sex":"男","age":18,"height":175,"date":[2013,8,11]},
{"id":2,"name":"小红","sex":"女","age":19,"height":165,"date":[2013,8,23]},
{"id":3,"name":"小强","sex":"男","age":20,"height":185,"date":[2013,9,1]}
],
"grade":"2"
}
// JavaBean类
class test {
private List student = new ArrayList();
private int grade;
public void setStudent(List student){
this.student = student;
}
public List getStudent(){
return student;
}
public void setGrade(int grade){
this.grade = grade;
}
public int getGrade(){
return grade;
}
private static class stu {
private int id;
private String name;
private String sex;
private int age;
private int height;
private int[] date;
public void setId(int id){
this.id = id;
}
public int getId(){
return id;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setSex(String sex){
this.sex = sex;
}
public String getSex(){
return sex;
}
public void setAge(int age){
this.age = age;
}
public int getAge(){
return age;
}
public void setHeight(int height){
this.height = height;
}
public int getHeight(){
return height;
}
public void setDate(int[] date){
this.date = date;
}
public int[] getDate(){
return date;
}
}
public String tostring(){
String str = "";
for (int i = 0;i
步骤2:利用Jackson方法进行解析
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ObjectMapper objectMapper = new ObjectMapper();
try {
// 1. //从assets获取json文件
InputStreamReader isr = new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream("assets/" + "student.json"),"utf-8");
BufferedReader bfr = new BufferedReader(isr);
String line;
StringBuilder stringBuilder = new StringBuilder();
while ((line = bfr.readLine())!=null){
stringBuilder.append(line);
}
// 2. 将JSON数据转化为字符串
System.out.println(stringBuilder.toString());
System.out.println(tes.tostring());
} catch (IOException e) {
e.printStackTrace();
}
}
}
JSON
XML
,具体请看文章Android:XML简介 & 解析方式对比(DOM、SAX、PULL)Android
中的知识进行深入讲解 ,有兴趣可以继续关注Carson_Ho的安卓开发笔记