json数据包含json对象,json数组,对象是{ },数组是[ ], 数组里面还可以包含json对象,json对象之间是用逗号(,)隔开
形式如下:
{ "languages":[ { "id":1,"ide":"VS","name":"C#"}, { "id":2,"ide":"eclipse","name":"java"}, { "id":3,"ide":"XCode","name":"Swift"} ], "category":"it"}
android studio下面新建assets(资产)文件夹,是放在main下面,和java,res同一目录下
在assets下新建test.json文件,把上面json数据放里面
下面是读取json文件输出到控制台显示:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.bt_showJson).setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.bt_showJson: ReadJson(); break; } } private void ReadJson() { try { InputStreamReader isr = new InputStreamReader(getAssets().open("test.json"), "utf-8"); BufferedReader br = new BufferedReader(isr); String line = ""; StringBuilder builder = new StringBuilder(); while ((line = br.readLine()) != null) { builder.append(line); } //json根对象 JSONObject root = new JSONObject(builder.toString()); System.out.println("category:" + root.getString("category")); //得到json数组 JSONArray array = root.getJSONArray("languages"); for (int i = 0; i < array.length(); i++) { //得到每一行的json对象 JSONObject lan = array.getJSONObject(i); System.out.println("----------------"); System.out.println("id:" + lan.getInt("id")); System.out.println("name:" + lan.getString("name")); System.out.println("ide:" + lan.getString("ide")); } } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } }
二:写入json数据,输出到控制台,新建一个WirteJson方法,然后点击按钮直接调用WirteJson函数
private void WirteJson() { try { //新建一个json根对象 JSONObject root = new JSONObject(); root.put("category", "it"); /* {"id":1,"ide":"VS","name":"C#"}, {"id":2,"ide":"eclipse","name":"java"}, {"id":3,"ide":"XCode","name":"Swift"}*/ //新建数组里面的json对象,新建3个对象,每个对象放入键值对 JSONObject lan1 = new JSONObject(); lan1.put("id", 1); lan1.put("ide", "vs"); lan1.put("name", "C#"); JSONObject lan2 = new JSONObject(); lan2.put("id", 2); lan2.put("ide", "eclipse"); lan2.put("name", "C#"); JSONObject lan3 = new JSONObject(); lan3.put("id", 3); lan3.put("ide", "Xcode"); lan3.put("name", "Swift"); //新建一个json数组 JSONArray array = new JSONArray(); array.put(lan1); array.put(lan2); array.put(lan3); //json数组放入json的root根对象里面 root.put("languages", array); System.out.println("------------下面是写入的json数据"); System.out.println(root.toString()); System.out.println("------------得到json数组对象"); System.out.println(root.getJSONArray("languages")); } catch (JSONException e) { e.printStackTrace(); } }
控制台的显示的数据是: