解析 Json
实例 Json 数据:
1 2 3 4 5 6 7 8
| { "name": "RED NENO", "age": 16, "hobby": [ {"game": "RainbowSix Siege"}, {"programming": "JavaScript"} ] }
|
添加 Gson 库
在项目 Gradle 配置文件中添加 Gson 库
1
| implementation 'com.google.code.gson:gson:2.8.5'
|
新建 JsonBean 类
1 2 3 4 5 6 7 8 9 10
| public class JsonBean { public String name; public int age; public Hobby hobby;
public static class Hobby { public String game; public String programming; } }
|
调用/获取数据
1 2 3 4 5 6 7 8 9 10 11 12
| String json = "{\n" + " \"name\": \"RED NENO\",\n" + " \"age\": 16,\n" + " \"hobby\": [\n" + " {\"game\": \"RainbowSix Siege\"},\n" + " {\"programming\": \"JavaScript\"}\n" + " ]\n" + "}"; JsonBean jsonBean = new Gson().fromJson(jsonStr, JsonBean.class);
|