JSON解析-Android原生解析

1.JSONObject

2.JSONArray

在src目录下 新建文件夹 assets

{
  "error_code":0,
  "reason": "Success",
  "result": {
    "data": [
      {
        "context": "灌篮高手",
        "hashId": "462sdf462sd4",
        "unixtime": 1466238232,
        "updatetime": "2012-12-12 12:12:12"
      },
      {
        "context": "数码宝贝",
        "hashId": "462sdf462sdf4",
        "unixtime": 1466238232,
        "updatetime": "2012-13-13 12:12:12"
      }
    ]
  }

}
package com.example.testapplication;

import android.content.res.AssetManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

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

import java.io.IOException;
import java.io.InputStream;

public class JsonDemoActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_json2);
    }

    public void parse(View view){
        String json = getJsonString();
        try {
            JSONObject jsonObject = new JSONObject(json);
            JSONObject result = jsonObject.getJSONObject("result");
            JSONArray jsonArray = result.getJSONArray("data");
            for (int i = 0; i<jsonArray.length();i++){
                JSONObject obj = jsonArray.getJSONObject(i);
                String content = obj.getString("context");
                Toast.makeText(getApplicationContext(), content, Toast.LENGTH_SHORT).show();
            }
        }catch (JSONException e){
            e.printStackTrace();
        }

    }

    // 读取数据
    public String getJsonString(){
        AssetManager assetManager = getAssets();
        InputStream in = null;

        try{
            in = assetManager.open("jokes.json");
            byte[] buffer = new byte[in.available()];
            in.read(buffer);
            String json = new String(buffer);
            return json;

        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
}

Guess you like

Origin blog.csdn.net/weixin_38107457/article/details/121482892