个性化阅读
专注于IT技术分析

android json解析教程

JSON(Javascript对象符号)是一种编程语言。它是最少的,文本的,是JavaScript的子集。它是XML的替代方法。

Android提供了解析JSON对象和数组的支持。

JSON优于XML的优势

1)对于AJAX应用程序,JSON比xml更快,更容易。

2)与XML不同,它的读写更短,更快。

3)它使用数组。


json对象

JSON对象包含键/值对,例如map。键是字符串,值是JSON类型。键和值之间以逗号分隔。 {(大括号)表示json对象。

{
    "employee": {
        "name":       "sachin", "salary":      56000, "married":    true
    }
}

json数组

[(方括号)代表json数组。

["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]

让我们再来看一个json数组的例子。

{ "Employee" :
    [
     {"id":"101", "name":"Sonoo Jaiswal", "salary":"50000"}, {"id":"102", "name":"Vimal Jaiswal", "salary":"60000"}
    ] 
}

Android JSON解析示例

activity_main.xml

从面板上拖动一个textview。现在,activity_main.xml文件将如下所示:

<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="75dp"
        android:layout_marginTop="46dp"
        android:text="TextView" />

</RelativeLayout>

活动类

让我们编写代码以使用dom解析器解析xml。

package com.srcmini.jsonparsing;

import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {
public static final String JSON_STRING="{\"employee\":{\"name\":\"Sachin\", \"salary\":56000}}";

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

TextView textView1=(TextView)findViewById(R.id.textView1);

try{
JSONObject emp=(new JSONObject(JSON_STRING)).getJSONObject("employee");
String empname=emp.getString("name");
int empsalary=emp.getInt("salary");

String str="Employee Name:"+empname+"\n"+"Employee Salary:"+empsalary;
textView1.setText(str);

}catch (Exception e) {e.printStackTrace();}

}

}


输出:

在Android中解析JSONArray

借助JSONArray类,你可以解析包含JSON对象的JSONArray。让我们看一下解析json数组的简单示例。

package com.example.jsonparsing2;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {
   @Override
    protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         
        TextView output = (TextView) findViewById(R.id.textView1);
         
        String strJson="{ \"Employee\" :[{\"id\":\"101\", \"name\":\"Sonoo Jaiswal\", \"salary\":\"50000\"}, {\"id\":\"102\", \"name\":\"Vimal Jaiswal\", \"salary\":\"60000\"}] }";
        
               String data = "";
               try {
                     // Create the root JSONObject from the JSON string.
            	   JSONObject  jsonRootObject = new JSONObject(strJson);

            	   //Get the instance of JSONArray that contains JSONObjects
                    JSONArray jsonArray = jsonRootObject.optJSONArray("Employee");
                   
                    //Iterate the jsonArray and print the info of JSONObjects
                    for(int i=0; i < jsonArray.length(); i++){
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                         
                        int id = Integer.parseInt(jsonObject.optString("id").toString());
                        String name = jsonObject.optString("name").toString();
                        float salary = Float.parseFloat(jsonObject.optString("salary").toString());
                         
                        data += "Node"+i+" : \n id= "+ id +" \n Name= "+ name +" \n Salary= "+ salary +" \n ";
                      }
                    output.setText(data);
                 } catch (JSONException e) {e.printStackTrace();}
      }
}


输出:

赞(0)
未经允许不得转载:srcmini » android json解析教程

评论 抢沙发

评论前必须登录!