Android 解析JSON
Posted 第三女神程忆难
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android 解析JSON相关的知识,希望对你有一定的参考价值。
安卓解析JSON
JSON解析
1、Gson
2、FastJson
3、原生解析
解析以下字符串
"code": 1024,
"message": "Today is 1024",
"data":
"name": "ThirdGoddess",
"age": 18,
"occupation": "android Developer"
对应Java实体类 PeopleEntity:
public class PeopleEntity
private int code;
private String message;
private Data data;
public int getCode()
return code;
public void setCode(int code)
this.code = code;
public String getMessage()
return message;
public void setMessage(String message)
this.message = message;
public Data getData()
return data;
public void setData(Data data)
this.data = data;
public class Data
private String name;
private int age;
private String occupation;
public String getName()
return name;
public void setName(String name)
this.name = name;
public int getAge()
return age;
public void setAge(int age)
this.age = age;
public String getOccupation()
return occupation;
public void setOccupation(String occupation)
this.occupation = occupation;
GSON解析
推荐使用这种方式
build引入
// https://mvnrepository.com/artifact/com.google.code.gson/gson
implementation 'com.google.code.gson:gson:2.9.1'
Java代码:
package com.example.test;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.google.gson.Gson;
public class MainActivity extends AppCompatActivity
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String jsonStr = "\\"code\\":1024,\\"message\\":\\"Today is 1024\\",\\"data\\":\\"name\\":\\"ThirdGoddess\\",\\"age\\":18,\\"occupation\\":\\"Android Developer\\"";
//Gson解析
PeopleEntity peopleEntity = new Gson().fromJson(jsonStr, PeopleEntity.class);
FastJson解析
一般后端使用FastJson解析
build.gradle引入
// https://mvnrepository.com/artifact/com.alibaba/fastjson
implementation 'com.alibaba:fastjson:2.0.16'
Java代码:
package com.example.test;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
public class MainActivity extends AppCompatActivity
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String jsonStr = "\\"code\\":1024,\\"message\\":\\"Today is 1024\\",\\"data\\":\\"name\\":\\"ThirdGoddess\\",\\"age\\":18,\\"occupation\\":\\"Android Developer\\"";
//FastJson解析
JSONObject jsonObject = JSONObject.parseObject(jsonStr);
jsonObject.getInteger("code");
jsonObject.getString("message");
//FastJson映射实体类
PeopleEntity peopleEntity = JSON.parseObject(jsonStr, PeopleEntity.class);
以上是关于Android 解析JSON的主要内容,如果未能解决你的问题,请参考以下文章