0.什么是Json
JavaScript Object Natation, 一种轻量级的数据交换格式, 与XML一样, 广泛被采用的客户端和服务端交互的解决方案!具有良好的可读和便于快速编写的特性。我们和服务器交互一般用得较多的数据传递方式都是 Json 字符串的形式,保存对象也可以写成一个 Json 字符串然后存储!
1.Json的格式
花括号 { } :每一个 { } 中是一个文本对象
中括号 [ ] :每一个 [ ] 中是一个数组
英文逗号 , :数据用 , 分隔
英文双引号 " " :每一个 " " 中是一个数组
" 键 " : " 值 " 键值对之间用逗号分隔
eg :一个简单的Json字符串:
[
{ "id":"1","name":"基神","age":"18" },
{ "id":"2","name":"B神","age":"18" },
{ "id":"3","name":"曹神","age":"18" }
]
2.Gson
用于处理Json的类
Gson使用前需先导入 项目目录/app/build.gradle中,dependencies下
(0)Gson对象
import com.google.gson.Gson;
//通过构造函数来获取
Gson gson = new Gson();
(1)Gson的简单使用
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private TextView text1;
private TextView text2;
private TextView text3;
private TextView text4;
private TextView text5;
private TextView text6;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text1 = findViewById(R.id.text1);
text2 = findViewById(R.id.text2);
text3 = findViewById(R.id.text3);
text4 = findViewById(R.id.text4);
text5 = findViewById(R.id.text5);
text6 = findViewById(R.id.text6);
Gson gson = new Gson();
E zs = new E("张三", 100, 18);
E ls = new E("李四", 101, 19);
String zsJson = gson.toJson(zs); //对象 转 Json
String lsJson = gson.toJson(ls); //类的 toString方法
text1.setText(zsJson);
text2 .setText(lsJson);
E zs2 = gson.fromJson(zsJson, E.class); //Json 转 对象
text3.setText(gson.toJson(zs2));
Map<Integer, String> map = new HashMap<>();
map.put(1, "1");
map.put(2, "2");
String mapJson = gson.toJson(map);
text4.setText(mapJson);
Type type = new TypeToken<Map<Integer, String>>(){/* 可以复写方法 */}.getType();
Map<Integer, String> map2 = gson.fromJson(mapJson, type);
text5.setText(gson.toJson(map2));
List<Map<Integer, String>> mapList = new ArrayList<>();
mapList.add(map);
text6.setText(gson.toJson(mapList));
}
private static class E {
private String name;
private int id;
private int age;
E(String name, int id, int age) {
this.name = name;
this.id = id;
this.age = age;
}
@Override
public String toString() {
return "E{" +
"name='" + name + '\'' +
", id=" + id +
", age=" + age +
'}';
}
}
界面展示
(2)Gson的不简单使用
//JsonArray 剥掉中括号
//JsonObject 剥掉花括号
JsonArray jsonArray = new JsonArray(JsonString);
jsonArray.length() //jsonArray数组长度
jsonObject.length() //一个json中有多少个键值对
好吧 是有点水了 ... 负荆请罪 哈哈哈哈哈