编写项目,包含一个Activity。Activity页面效果如下图所示。点击按钮“解析文件1”后解析Json文件json_single并将结果显示在红色框体中,点击按钮“解析文件2”后解析Json文件json_multiple并将结果显示在红色框体中(有多条数据,建议使用列表控件ListView进行信息展示)。

 

 

 先写xml布局文件

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:layout_width="match_parent"
 4     android:layout_height="match_parent"
 5     android:orientation="vertical">
 6 
 7     <Button
 8         android:id="@+id/button50"
 9         android:layout_width="match_parent"
10         android:layout_height="wrap_content"
11 
12         android:text="解析文件1" />
13     <Button
14         android:id="@+id/button51"
15         android:layout_width="match_parent"
16         android:layout_height="wrap_content"
17         android:text="解析文件2" />
18     <ListView
19         android:layout_width="match_parent"
20         android:layout_height="wrap_content"
21         android:id="@+id/LS"/>
22 </LinearLayout>

将我们的JSON文件导入到res的raw下,如果没有raw,右键Andrriod Resource Directory在Resource type中输入raw,ok

json_single.json :

1 {
2     "name":"王小二",
3     "age":25,
4     "birthday":"1990-01-01",
5     "school":"师大",
6     "car":"比亚迪",
7     "house":"宿舍",
8 }

json_multiple.json :

 1 [{
 2     "name":"王小二",
 3     "age":25,
 4     "birthday":"1990-01-01",
 5     "school":"师大",
 6     "car":"比亚迪",
 7     "house":"宿舍",
 8 },
 9 {
10     "name":"李三",
11     "age":30,
12     "birthday":"1987-04-13",
13     "school":"清华",
14     "car":"大众速腾",
15     "house":"公寓",
16 },
17 {
18     "name":"张盼盼",
19     "age":17,
20     "birthday":"1995-07-02",
21     "school":"北大",
22     "car":"宝马7系",
23     "house":"别墅",
24 }]

思路很简单,就是读取到json文件然后解析最后显示出来。

Mainactiviyt : 

  1 package com.example.app;
  2 
  3 import androidx.annotation.RequiresApi;
  4 import androidx.appcompat.app.AppCompatActivity;
  5 
  6 import android.Manifest;
  7 import android.annotation.SuppressLint;
  8 import android.os.Build;
  9 import android.os.Bundle;
 10 import android.view.View;
 11 import android.view.ViewGroup;
 12 import android.view.LayoutInflater;
 13 
 14 import android.widget.*;
 15 import org.json.*;
 16 import org.json.JSONException;
 17 import org.json.JSONObject;
 18 import java.io.BufferedReader;
 19 import java.io.FileOutputStream;
 20 import java.io.FileInputStream;
 21 import java.io.IOException;
 22 import java.io.InputStream;
 23 import java.io.InputStreamReader;
 24 import java.security.Permission;
 25 import java.security.Permissions;
 26 import java.io.UnsupportedEncodingException;
 27 
 28 
 29 public class MainActivity extends AppCompatActivity {
 30 
 31     private static String[] Json; //用来存储的数组
 32     private ListView LS;
 33     private Button B1;
 34     private Button B2;
 35     private int a = 0;
 36 
 37     @Override
 38     protected void onCreate(Bundle savedInstanceState) {
 39         super.onCreate(savedInstanceState);
 40         setContentView(R.layout.homework_8_2);
 41 
 42         B1 = (Button) findViewById(R.id.button50);
 43         B2 = (Button) findViewById(R.id.button51);
 44         LS = (ListView) findViewById(R.id.LS); //实例化按钮B1,B2,和listview
 45         B1.setOnClickListener(new View.OnClickListener() {//监听B1
 46             @Override
 47             public void onClick(View v) {
 48                 //Json = new String[100];
 49                 JsonDataToString1(); //读取json文件
 50             }
 51         });
 52         B2.setOnClickListener(new View.OnClickListener() {//监听B2
 53             @Override
 54             public void onClick(View v) {
 55                 //Json = new String[100];
 56                 a = 0; //当B2被点击,变量a就会重置为0
 57                 JsonDataToString2(); //读取json文件
 58             }
 59         });
 60     }
 61     @SuppressLint("ResourceType")
 62     private void JsonDataToString1(){
 63 
 64         InputStreamReader inputStreamReader = null;
 65         String jsonData = "";
 66         try {
 67             inputStreamReader = new InputStreamReader(getResources().openRawResource(R.raw.json_single),"UTF-8");//读取
 68             BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
 69             String line;
 70             StringBuilder srt = new StringBuilder();
 71             while((line = bufferedReader.readLine()) != null){
 72                 srt.append(line);
 73             }
 74             inputStreamReader.close();
 75             bufferedReader.close();
 76             jsonData = srt.toString(); //以上就是读取json文件,转化成string
 77         }catch (UnsupportedOperationException e){
 78             e.printStackTrace();
 79         }catch (IOException e){
 80             e.printStackTrace();
 81         }
 82 
 83         if (jsonData != ""){
 84             getDataFromData1(jsonData); //进一步分析字符串,获取json内容
 85         }else {
 86             Toast.makeText(MainActivity.this,"error",Toast.LENGTH_SHORT).show();
 87         }
 88         }
 89 
 90         private void getDataFromData1(String jsonData){
 91         try{
 92 
 93             JSONObject jsonObject = new JSONObject(jsonData);
 94             String name = jsonObject.getString("name");
 95             String age = jsonObject.getString("age");
 96             String birthday = jsonObject.getString("birthday");
 97             String school = jsonObject.getString("school");
 98             String car = jsonObject.getString("car");
 99             String house = jsonObject.getString("house"); //获取json内容
100             Json = new String[]{
101                     "name:"+name,"age:"+age,"birthday:"+birthday,"school:"+school,"car:"+car,"house:"+house
102             };//将json内容存进数组中
103             ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,R.id.LS);//新建并配置ArrayAapeter
104             MyBaseAdapter mAdapter = new MyBaseAdapter();
105             LS.setAdapter(mAdapter);
106         }catch (JSONException e){
107             e.printStackTrace();
108         }
109         }
110 
111     @SuppressLint("ResourceType")
112     private void JsonDataToString2(){
113 
114         InputStreamReader inputStreamReader = null;
115         String jsonData = "";
116         try {
117             inputStreamReader = new InputStreamReader(getResources().openRawResource(R.raw.json_multiple),"UTF-8");//读取
118             BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
119             String line;
120             StringBuilder srt = new StringBuilder();
121             while((line = bufferedReader.readLine()) != null){
122                 srt.append(line);
123             }
124             inputStreamReader.close();
125             bufferedReader.close();
126             jsonData = srt.toString();//以上就是读取json文件,转化成string
127         }catch (UnsupportedOperationException e){
128             e.printStackTrace();
129         }catch (IOException e){
130             e.printStackTrace();
131         }
132 
133         if (jsonData != ""){
134             getDataFromData2(jsonData); //进一步分析字符串,获取json内容
135         }else {
136             Toast.makeText(MainActivity.this,"error",Toast.LENGTH_SHORT).show();
137         }
138     }
139 
140     private void getDataFromData2(String jsonData){
141         try{
142             Json = new String[100]; //这里必须初始化Json数组,否则点击完解析一后Json数组的length只有6,会因空间不足而程序崩溃
143             JSONArray jsonArray = new JSONArray(jsonData);
144             //String[] bbk = new String[]{};
145             for (int i=0;i<jsonArray.length();i++){ //会循环三次
146                 JSONObject jsonObject = jsonArray.getJSONObject(i);
147                 String name = jsonObject.getString("name");
148                 String age = jsonObject.getString("age");
149                 String birthday = jsonObject.getString("birthday");
150                 String school = jsonObject.getString("school");
151                 String car = jsonObject.getString("car");
152                 String house = jsonObject.getString("house");//解析出json的内容
153                 Json[a] = "name:"+name;  //为了将数据循环存储进Json数组中,用了一个变量a来控制
154                 Json[a+1] = "age:"+age;
155                 Json[a+2] = "birthday:"+birthday;
156                 Json[a+3] = "school:"+school;
157                 Json[a+4] = "car:"+car;
158                 Json[a+5] = "house:"+house; //因为发现数据有六项且key值都一样,就正好用一个变量a来表示数组的下标
159                 a = a+6;  //如果a不重置为0,那么a会不停的往上加,直到超出数组下标溢出,导致程序崩溃
160             }
161             ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,R.id.LS);//新建并配置ArrayAapeter
162             MyBaseAdapter mAdapter = new MyBaseAdapter();
163             LS.setAdapter(mAdapter);
164         }catch (JSONException e){
165             e.printStackTrace();
166         }
167     }
168 
169     class MyBaseAdapter extends BaseAdapter{ //这里不解释
170 
171         @Override
172         public int getCount() {
173             return Json.length;
174         }
175         @Override
176         public Object getItem(int position) {
177             return null;
178         }
179         @Override
180         public long getItemId(int position) {
181             return 0;
182         }
183         @Override
184         public View getView(int position, View convertView, ViewGroup parent) {
185             ViewHolder holder;
186             if(convertView == null){
187                 convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.homework_five_2,parent,false);
188                 holder = new ViewHolder();
189                 holder.mTextView = (TextView) convertView.findViewById(R.id.tv);
190                 convertView.setTag(holder);
191             }else {
192                 holder = (ViewHolder) convertView.getTag();
193             }
194             holder.mTextView.setText(Json[position]);
195             return convertView;
196         }
197         class ViewHolder {
198             TextView mTextView;
199         }
200     }
201 
202 }

我们的布局文件用的listview,所以我们需要再写一个布局文件提供格式

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     xmlns:app="http://schemas.android.com/apk/res-auto"
 4     android:layout_width="match_parent"
 5     android:layout_height="match_parent">
 6 
 7     <TextView
 8         android:id="@+id/tv"
 9         android:layout_width="match_parent"
10         android:layout_height="match_parent"/>
11 
12 </LinearLayout>

结果如图

最后,赶时间写出来的,写的很烂,等过几天精简一下代码,等待更新哦!

 

版权声明:本文为rebirther原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/rebirther/p/12888087.html