Android JSON 解析示例

JSON解析
本文介绍如何在Android应用中使用JSON进行数据解析,并提供了一个完整的示例,展示如何从JSON字符串中提取数据并将其显示在ListView上。

一般来说,JSON(JavaScript 对象表示法)是用于交换来自服务器的数据的最简单的数据交换格式之一,它是 XML 的最佳替代方案。简单来说,我们可以说 JSON 是一种轻量级的结构化语言。

 

Android 支持JSONObjectJSONArrayJSONStringer等所有 JSON 类解析 JSON 数据以获取 android 应用程序中所需的信息。

 

JSON 的主要优点是,它独立于语言,JSON 对象将包含键/值对等数据。

 

以下是 Android 应用程序中 JSON 数据的示例结构。

{

    "users": [

        {

            "name": "Suresh Dasari",

            "designation": "Team Leader",

            "location": "Hyderabad"
        },

        {

            "name": "Rohini Alavala",

            "designation": "Agricultural Officer",

            "location": "Guntur"
        }

    ]
}

通常,JSON 节点将以方括号[ ) 或花括号{ ) 开头。方括号和大括号的区别在于,方括号[)代表一个JSONArray节点的开始,而大括号{)代表一个JSONObject,所以我们需要调用适当的方法来获取数据。

 

如果 JSON 数据以[开头,那么我们需要使用getJSONArray()方法来获取数据,同样如果它以{开头,那么我们需要使用getJSONObject()方法。

Android 中的 JSON 解析

要在 android 中解析 JSON 数据,我们需要创建一个JSONObjectJSONArray对象的实例,其中包含一个包含 JSON 数据的字符串。

 

以下是使用 JSONObject 和 JSONArray 对象在 android 中解析 JSON 数据以从 JSON 对象中获取所需信息的代码片段。

 

JSONObject jObj = new JSONObject(jsonStr);
JSONArray jsonArry = jObj.getJSONArray("users");
for(int i=0;i<jsonArry.length();i++){
    HashMap<String,String> user = new HashMap<>();
    JSONObject obj = jsonArry.getJSONObject(i);
    user.put("name",obj.getString("name"));
    user.put("designation",obj.getString("designation"));
    user.put("location",obj.getString("location"));
    userList.add(user);
}

如果您观察上面的代码片段,我们使用JSONObjectJSONArray对象来解析数据以从包含 JSON 数据的字符串中获取所需的信息。

 

现在我们将通过示例了解如何解析 JSON 字符串并将解析后的 JSON 绑定到Android 应用程序中的Listview

Android JSON 解析示例

以下是在 Android 应用程序中使用JSON类解析 JSON 字符串并从中获取所需信息的示例。

 

使用 android studio 创建一个新的 android 应用程序并将名称命名为JsonParserExample。如果您不知道在 android studio 中创建应用程序,请查看这篇文章Android Hello World App

 

现在从\res\layout文件夹路径中打开activity_main.xml文件并编写如下所示的代码。

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <ListView
        android:id="@+id/user_list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:dividerHeight="1dp" />
</LinearLayout>

之后在/res/layout文件夹中创建另一个布局文件 ( list_row.xml ) 以在listview中显示数据 ,为此右键单击布局文件夹 → 添加新布局资源文件→ 命名为list_row.xml并编写如下代码如下所示。 

list_row.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="5dip" >
    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:textSize="17dp" />
    <TextView
        android:id="@+id/designation"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/name"
        android:layout_marginTop="7dp"
        android:textColor="#343434"
        android:textSize="14dp" />
    <TextView
        android:id="@+id/location"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/designation"
        android:layout_alignBottom="@+id/designation"
        android:layout_alignParentRight="true"
        android:textColor="#343434"
        android:textSize="14dp" />
</RelativeLayout>

现在从\java\com.tutlane.jsonparserexample路径打开你的主要活动文件MainActivity.java并编写如下所示的代码

MainActivity.java

package com.tutlane.jsonparserexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String jsonStr = getListData();
        try{
            ArrayList<HashMap<String, String>> userList = new ArrayList<>();
            ListView lv = (ListView) findViewById(R.id.user_list);
            JSONObject jObj = new JSONObject(jsonStr);
            JSONArray jsonArry = jObj.getJSONArray("users");
            for(int i=0;i<jsonArry.length();i++){
                HashMap<String,String> user = new HashMap<>();
                JSONObject obj = jsonArry.getJSONObject(i);
                user.put("name",obj.getString("name"));
                user.put("designation",obj.getString("designation"));
                user.put("location",obj.getString("location"));
                userList.add(user);
            }
            ListAdapter adapter = new SimpleAdapter(MainActivity.this, userList, R.layout.list_row,new String[]{"name","designation","location"}, new int[]{R.id.name, R.id.designation, R.id.location});
            lv.setAdapter(adapter);
        }
        catch (JSONException ex){
            Log.e("JsonParser Example","unexpected JSON exception", ex);
        }
    }
    private String getListData() {
        String jsonStr = "{ \"users\" :[" +
                "{\"name\":\"Suresh Dasari\",\"designation\":\"Team Leader\",\"location\":\"Hyderabad\"}" +
                ",{\"name\":\"Rohini Alavala\",\"designation\":\"Agricultural Officer\",\"location\":\"Guntur\"}" +
                ",{\"name\":\"Trishika Dasari\",\"designation\":\"Charted Accountant\",\"location\":\"Guntur\"}] }";
        return jsonStr;
    }
}


 

如果您观察上面的代码,我们使用JSONObjectJSONArray对象根据我们的要求从 JSON 字符串中解析并获取所需的数据。

Android JSON 解析示例的输出

当我们在 android studio 中运行上述程序时,我们将得到如下所示的结果。

 

Android JSON 解析示例结果

 

这就是我们如何在 android 应用程序中解析 JSON 数据以根据我们的要求获取所需信息的方式。 

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值