android之JSON解析

Json解析

JavaScrip對象表示法(JavaScript Object Notation)JSON屬於輕量級文本數據交換格式
JSon獨立於平臺和語言JSON具有自我描述性更易於理解
類似Xml,比Xml更小,更快,更易解析

  • Json文件

數據保存在{key: value}(鍵值對)中
{“info”:{“name”:”jack”,”age:”20,”salary”:3000,”愛好”:[“看電影”,”打代碼”,”跑步”]}}

  • Json語法

Key數據類型:
String
Value數據類型:
{} JsonObject 類型
[] 數組類型
String 字符串類型
Int,float 數值類型

  • Json解析相關類

JsonObject
Json對象,裏面包含一個或多個鍵值對
JSONArray
Json數組,內部元素由鏈表管理
//取出json屬豬中下標爲index的元素
jsonArray.getString(index);
//Json數組中的元素可以爲任意類型
JsonArray。getInt(index);
JsonArray.getJSONObject(index);
JsonArray.getJSONArray(index);
例子
MainActivity.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;

public class MainActivity extends Activity implements OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.button1).setOnClickListener(this);
        findViewById(R.id.button2).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        if (v.getId() == R.id.button1) {
            // 解析Json
            readJson("info.json");
        } else if (v.getId() == R.id.button2) {
            // 打包json
            // {"info": {"name":"think in java", "price":100,"author":["Jack","Lily"]}, "number":50}
            closeJson();
        }
    }
    private void closeJson(){

            JSONObject obj=new JSONObject();
            try {
                obj.put("number", 50);

                JSONObject infoobj=new JSONObject();
                infoobj.put("name", "thingk in java");
                infoobj.put("price", 100);
                JSONArray array=new JSONArray();
                array.put(0, "Jack");
                array.put(1, "Lily");
                obj.put("author", array);
                obj.put("info", infoobj);

                Log.d("Tag", ""+obj);

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }
    private void readJson(String string) {
        try {
             InputStream is = this.getResources().getAssets().open(string);
             InputStreamReader isr=new InputStreamReader(is);
             BufferedReader br=new BufferedReader(isr);
             String json = br.readLine();
             Log.d("Tag", json);
             //創建json對象
             JSONObject obj = new JSONObject(json);
             //key爲info的內容
             JSONObject infoObj=obj.getJSONObject("info");
             //取出名字
             String name=infoObj.getString("name");
             //取出年齡
             int age=infoObj.getInt("age");
             //取出收入
             int salary = infoObj.getInt("salary");
             Log.d("Tag", "name = "+name+",age = "+age+",+salary = "+salary);

             JSONArray array=infoObj.getJSONArray("favor");
             for (int i = 0; i < array.length(); i++) {
                String favor = array.getString(i);
                Log.d("Tag", "favor = "+favor);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.android_830_json.MainActivity" >
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="103dp"
        android:text="解析Json" />
    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_below="@+id/button1"
        android:layout_marginTop="100dp"
        android:text="打包Json" />
</RelativeLayout>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章