数据解析之JSON

本文介绍了JSON在网络传输中的优势,通过示例详细展示了如何使用JSONObject和GSON进行JSON数据的解析。包括新建JSON文件,使用JSONObject的代码示例,以及GSON库的依赖引入,如何将JSON字符串映射为对象和解析JSON数组的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

JSON的优势是体积更小,网络传输的时候可以省流量,但它语义性差。

新建get_data.json,放在XAMPP安装目录下的htdocs中

[
{"id":5,"version":5.5,"name":"Clash of Clans"},
{"id":6,"version":7.0,"name":"Boom Beach"},
{"id":7,"version":3.5,"name":"Clash Royale"}
]

使用JSONObject

MainActivity添加代码

//JSONObject解析JSON
    private void parseJSONWithJSONObject(String responseData) {
        try {
            JSONArray jsonArray = new JSONArray(responseData);
            int size = jsonArray.length();
            for (int i = 0; i < size; i++) {

                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String id = jsonObject.getString("id");
                String name = jsonObject.getString("name");
                String version = jsonObject.getString("version");
                Log.e("MainActivity", "id is " + id);
                Log.e("MainActivity", "name is " + name);
                Log.e("MainActivity", "version is " + version);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

运行结果


使用GSON

添加依赖

 implementation 'com.google.code.gson:gson:2.8.0'

GSON可以将一段JSON格式的字符串自动映射成一个对象

若是解析一段JSON数据如下,定义Person类,并添加name和age字段

{"name":"Tom","age":20}

解析代码为

Gson gson = new Gson();

Person person = gson.fromJson(jsonData,Person.class);

若解析的是JSON数组,需要借助TypeToken将期望解析成的数组类型传入到fromJson()方法中,解析代码如下

List<Person>people = gson.fromJson(jsonData,new TypeToken<List<Person>>(){}.getType());

新建App类

public class App {
    private String id;
    private String name;
    private String version;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }
}

修改MainActivity代码

sendRequest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //指定访问的服务器地址是电脑本机  http://10.0.2.2 对模拟器来说就是电脑本机的IP地址
                sendRequestWithOkHttp("http://10.0.2.2/get_data.json");
            }
        });
 //GSON解析JSON
    private void parseJSONWithGSON(String responseData) {
        Gson gson = new Gson();
        List<App> appList = gson.fromJson(responseData,new TypeToken<List<App>>(){}.getType());

        for (App app:appList){
            Log.e("MainActivity", "id is " + app.getId());
            Log.e("MainActivity", "name is " + app.getName());
            Log.e("MainActivity", "version is " + app.getVersion());
        }
    }

运行结果


MainActivity完整代码

public class MainActivity extends AppCompatActivity {
    AppCompatTextView responseText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        responseText = findViewById(R.id.response_text);
        AppCompatButton sendRequest = findViewById(R.id.send_request);
        responseText = findViewById(R.id.response_text);
        sendRequest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //指定访问的服务器地址是电脑本机  http://10.0.2.2 对模拟器来说就是电脑本机的IP地址
                sendRequestWithOkHttp("http://10.0.2.2/get_data.json");
            }
        });
    }

    //OkHttp
    private void sendRequestWithOkHttp(final String url) {
        new Thread(new Runnable() {
            @Override
            public void run() {

                try {

                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url(url)
                            .build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    parseJSONWithGSON(responseData);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //GSON解析JSON
    private void parseJSONWithGSON(String responseData) {
        Gson gson = new Gson();
        List<App> appList = gson.fromJson(responseData,new TypeToken<List<App>>(){}.getType());

        for (App app:appList){
            Log.e("MainActivity", "id is " + app.getId());
            Log.e("MainActivity", "name is " + app.getName());
            Log.e("MainActivity", "version is " + app.getVersion());
        }
    }

    //JSONObject解析JSON
    private void parseJSONWithJSONObject(String responseData) {
        try {
            JSONArray jsonArray = new JSONArray(responseData);
            int size = jsonArray.length();
            for (int i = 0; i < size; i++) {

                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String id = jsonObject.getString("id");
                String name = jsonObject.getString("name");
                String version = jsonObject.getString("version");
                Log.e("MainActivity", "id is " + id);
                Log.e("MainActivity", "name is " + name);
                Log.e("MainActivity", "version is " + version);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void parseXMLWithSAX(String responseData) {
        try {
            SAXParserFactory factory = SAXParserFactory.newInstance();
            XMLReader xmlReader = factory.newSAXParser().getXMLReader();
            ContentHandler handler = new ContentHandler();
            //将ContentHandler的实例设置到XMLReader中
            xmlReader.setContentHandler(handler);
            //开始执行解析
            xmlReader.parse(new InputSource(new StringReader(responseData)));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //HttpURLConnection
    private void sendRequestWithHttpURLConnection(final String connectionUrl) {
        //开启线程发起网络请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                BufferedReader reader = null;
                try {
                    URL url = new URL(connectionUrl);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    InputStream in = connection.getInputStream();
                    //对获取的输入流进行读取
                    reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    showResponse(response.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

    //Pull解析XML
    private void parseXMLWithPull(String responseData) {
        try {
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            XmlPullParser xmlPullParser = factory.newPullParser();
            xmlPullParser.setInput(new StringReader(responseData));
            //得到当前的解析事件
            int eventType = xmlPullParser.getEventType();
            String id = null;
            String name = null;
            String version = null;
            while (eventType != XmlPullParser.END_DOCUMENT) {
                String nodeName = xmlPullParser.getName();
                switch (eventType) {
                    //开始解析某个节点
                    case XmlPullParser.START_TAG: {
                        if ("id".equals(nodeName)) {
                            //nextText() 获取节点内具体的内容
                            id = xmlPullParser.nextText();
                        } else if ("name".equals(nodeName)) {
                            name = xmlPullParser.nextText();
                        } else if ("version".equals(nodeName)) {
                            version = xmlPullParser.nextText();
                        }
                        break;
                    }
                    //完成解析某个节点
                    case XmlPullParser.END_TAG: {
                        if ("app".equals(nodeName)) {//完成app节点的解析
                            Log.e("MainActivity", "id is " + id);
                            Log.e("MainActivity", "name is " + name);
                            Log.e("MainActivity", "version is " + version);
                        }
                        break;
                    }
                    default:
                        break;
                }
                //获取下一个解析事件
                eventType = xmlPullParser.next();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showResponse(final String response) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //在这里进行UI操作,将结果显示到界面上
                responseText.setText(response);
            }
        });

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值