原生JSON解析

Posted 钱大少丶

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了原生JSON解析相关的知识,希望对你有一定的参考价值。

原生JSON解析

JSONObject:JSON数据封装对象
JSONArray:JSON数据封装数组

布局:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout
 3     android:orientation="vertical"
 4     xmlns:android="http://schemas.android.com/apk/res/android"
 5     xmlns:app="http://schemas.android.com/apk/res-auto"
 6     xmlns:tools="http://schemas.android.com/tools"
 7     android:layout_width="match_parent"
 8     android:layout_height="match_parent"
 9     tools:context="net.bwie.jsonobject.MainActivity">
10 
11     <Button
12         android:id="@+id/read_file_btn"
13         android:layout_width="wrap_content"
14         android:layout_height="wrap_content"
15         android:text="读取文件中的json数据"/>
16 
17     <Button
18         android:id="@+id/parse_btn"
19         android:layout_width="wrap_content"
20         android:layout_height="wrap_content"
21         android:text="解析json数据"/>
22 
23     <TextView
24         android:id="@+id/result_tv"
25         android:layout_width="wrap_content"
26         android:layout_height="wrap_content"
27         android:text="Hello World!"/>
28 
29 </LinearLayout>

Bean:

  1 package net.bwie.jsonobject;
  2 
  3 import java.util.List;
  4 
  5 public class ShoppingBean {
  6 
  7     private String msg;
  8     private InfoBean info;
  9 
 10     public String getMsg() {
 11         return msg;
 12     }
 13 
 14     public void setMsg(String msg) {
 15         this.msg = msg;
 16     }
 17 
 18     public InfoBean getInfo() {
 19         return info;
 20     }
 21 
 22     public void setInfo(InfoBean info) {
 23         this.info = info;
 24     }
 25 
 26     @Override
 27     public String toString() {
 28         return "ShoppingBean{" +
 29                 "msg=‘" + msg + ‘\‘‘ +
 30                 ", info=" + info +
 31                 ‘}‘;
 32     }
 33 
 34     public static class InfoBean {
 35 
 36         private int cat_id;
 37         private List<GoodsBean> good;
 38         private boolean url;
 39 
 40         public int getCat_id() {
 41             return cat_id;
 42         }
 43 
 44         public void setCat_id(int cat_id) {
 45             this.cat_id = cat_id;
 46         }
 47 
 48         public List<GoodsBean> getGood() {
 49             return good;
 50         }
 51 
 52         public void setGood(List<GoodsBean> good) {
 53             this.good = good;
 54         }
 55 
 56         public boolean isUrl() {
 57             return url;
 58         }
 59 
 60         public void setUrl(boolean url) {
 61             this.url = url;
 62         }
 63 
 64         @Override
 65         public String toString() {
 66             return "InfoBean{" +
 67                     "cat_id=" + cat_id +
 68                     ", good=" + good +
 69                     ", url=" + url +
 70                     ‘}‘;
 71         }
 72 
 73         public static class GoodsBean {
 74 
 75             private long add_time;
 76             private String colorcode;
 77             private String currency_price;
 78             private String description;
 79             private String goods_id;
 80             private String goods_name;
 81             private String thumb;
 82 
 83             public long getAdd_time() {
 84                 return add_time;
 85             }
 86 
 87             public void setAdd_time(long add_time) {
 88                 this.add_time = add_time;
 89             }
 90 
 91             public String getColorcode() {
 92                 return colorcode;
 93             }
 94 
 95             public void setColorcode(String colorcode) {
 96                 this.colorcode = colorcode;
 97             }
 98 
 99             public String getCurrency_price() {
100                 return currency_price;
101             }
102 
103             public void setCurrency_price(String currency_price) {
104                 this.currency_price = currency_price;
105             }
106 
107             public String getDescription() {
108                 return description;
109             }
110 
111             public void setDescription(String description) {
112                 this.description = description;
113             }
114 
115             public String getGoods_id() {
116                 return goods_id;
117             }
118 
119             public void setGoods_id(String goods_id) {
120                 this.goods_id = goods_id;
121             }
122 
123             public String getGoods_name() {
124                 return goods_name;
125             }
126 
127             public void setGoods_name(String goods_name) {
128                 this.goods_name = goods_name;
129             }
130 
131             public String getThumb() {
132                 return thumb;
133             }
134 
135             public void setThumb(String thumb) {
136                 this.thumb = thumb;
137             }
138 
139             @Override
140             public String toString() {
141                 return "GoodsBean{" +
142                         "add_time=" + add_time +
143                         ", colorcode=‘" + colorcode + ‘\‘‘ +
144                         ", currency_price=‘" + currency_price + ‘\‘‘ +
145                         ", description=‘" + description + ‘\‘‘ +
146                         ", goods_id=‘" + goods_id + ‘\‘‘ +
147                         ", goods_name=‘" + goods_name + ‘\‘‘ +
148                         ", thumb=‘" + thumb + ‘\‘‘ +
149                         ‘}‘;
150             }
151         }
152 
153     }
154 
155 }

Activity:

  1 /**
  2  * 1、将json文件存在外部存储中,使用IO流读取文件中的数据
  3  * 2、使用JSONObject解析读取出来的数据
  4  */
  5 public class MainActivity extends AppCompatActivity implements View.OnClickListener {
  6 
  7     private String mJson = "";
  8 
  9     protected Button mReadFileBtn;
 10     protected Button mParseBtn;
 11     protected TextView mResultTv;
 12 
 13     @Override
 14     protected void onCreate(Bundle savedInstanceState) {
 15         super.onCreate(savedInstanceState);
 16         super.setContentView(R.layout.activity_main);
 17         initView();
 18     }
 19 
 20     @Override
 21     public void onClick(View view) {
 22         if (view.getId() == R.id.read_file_btn) {
 23             readFile();
 24         } else if (view.getId() == R.id.parse_btn) {
 25             ShoppingBean shopping = parseJson();
 26             Log.d("1507", "" + shopping);
 27         }
 28     }
 29 
 30     // 解析JSON数据
 31     // 遇到{}就创建JSONObject,遇到[]就创建JSONArray
 32     private ShoppingBean parseJson() {
 33         ShoppingBean shopping = null;
 34         try {
 35             JSONObject rootObject = new JSONObject(mJson);
 36          shopping = new ShoppingBean();
 37 
 38             String msg = rootObject.getString("msg");
 39             shopping.setMsg(msg);
 40 
 41             JSONObject infoObject = rootObject.getJSONObject("info");
 42             ShoppingBean.InfoBean info = new ShoppingBean.InfoBean();
 43             shopping.setInfo(info);
 44 
 45             int catId = infoObject.getInt("cat_id");
 46             info.setCat_id(catId);
 47 
 48             boolean url = infoObject.getBoolean("url");
 49             info.setUrl(url);
 50 
 51             JSONArray goodsArray = infoObject.getJSONArray("goods");
 52             List<ShoppingBean.InfoBean.GoodsBean> goodsList = new ArrayList<>();
 53             info.setGood(goodsList);
 54 
 55             for (int i = 0; i < goodsArray.length(); i++) {
 56                 JSONObject goodsObject = goodsArray.getJSONObject(i);
 57                 ShoppingBean.InfoBean.GoodsBean goods = new ShoppingBean.InfoBean.GoodsBean();
 58 
 59                 long addTime = goodsObject.getLong("add_time");
 60                 goods.setAdd_time(addTime);
 61 
 62                 String colorCode = goodsObject.getString("colorcode");
 63                 goods.setColorcode(colorCode);
 64 
 65                 String currencyPrice = goodsObject.getString("currency_price");
 66                 goods.setCurrency_price(currencyPrice);
 67 
 68                 String description = goodsObject.getString("description");
 69                 goods.setDescription(description);
 70 
 71                 String goodsName = goodsObject.getString("goods_name");
 72                 goods.setGoods_name(goodsName);
 73 
 74                 String thumb = goodsObject.getString("thumb");
 75                 goods.setThumb(thumb);
 76 
 77                 goodsList.add(goods);
 78             }
 79 
 80         } catch (Exception e) {
 81             e.printStackTrace();
 82         }
 83 
 84         return shopping;
 85 
 86     }
 87 
 88     // 读取文件中的JSON数据
 89     private void readFile() {
 90         // 根目录
 91         // Environment.getExternalStorageDirectory()
 92 
 93         // 外部存储公共路径,例如:DCIM,DOWNLOADS等系统提供的文件夹
 94 //        Environment.getExternalStoragePublicDirectory(类型)
 95 
 96         // 外部存储私有路径:Android文件夹
 97 //        context.getExternalFilesDir(null)
 98 
 99         // downloads文件夹路径
100         String filePath = Environment
101                 .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
102                 .getAbsolutePath();
103         String fileName = "json.txt";
104 
105         File file = new File(filePath, fileName);
106 
107         // 文件字符输入流
108         // 字缓符输入冲流
109         BufferedReader br = null;
110         try {
111             br = new BufferedReader(new FileReader(file));
112             String line = new String();
113             while ((line = br.readLine()) != null) {
114                 mJson += line;
115             }
116             if (mJson != null) {
117                 mResultTv.setText(mJson);
118             }
119         } catch (Exception e) {
120             e.printStackTrace();
121         } finally {
122             try {
123                 br.close();
124             } catch (IOException e) {
125                 e.printStackTrace();
126             }
127         }
128     }
129 
130     private void initView() {
131         mReadFileBtn = (Button) findViewById(R.id.read_file_btn);
132         mReadFileBtn.setOnClickListener(MainActivity.this);
133         mParseBtn = (Button) findViewById(R.id.parse_btn);
134         mParseBtn.setOnClickListener(MainActivity.this);
135         mResultTv = (TextView) findViewById(R.id.result_tv);
136     }
137 }

权限:

  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

 


以上是关于原生JSON解析的主要内容,如果未能解决你的问题,请参考以下文章

片段中的 JSON 解析 [关闭]

java中把json怎么转换成数组?

原生JSON解析

json原生解析

怎么将json对象添加进json数组中

解析:JSON 文本没有以数组或对象开头,并且允许未设置片段的选项