JSON:JavaScript 对象表示法(JavaScriptObject Notation)。独立于语言和平台,比 XML 更小、更快,更易解析。本课时介绍JSON数据格式。
Android平台自带了JSON解析的相关API,可以将文件、输入流中的数据转化为JSON对象,然后从对象中获取JSON保存的数据内容。本课时讲解读取JSON格式数据。
Android平台自带了JSON构造的相关API,可以轻松地构造JSON对象、JSON数组,并且为他们赋值,而且很容易将JSON对象转换为字符串用于传播。本课时讲解创建JSON格式数据。
创建一个新的工程LearnTestJSON,一个空的Activity |
创建一个test.JSON文件并copy到Asset目录(可用记事本编辑保存成utf-8编码方式) |
{ "languages":[ {"id":1,"ide":"Eclipse","name":"java"}, {"id":2,"ide":"Xcode","name":"Swift"}, {"id":3,"ide":"Visual Studio","name":"C#"} ], "cat":"it"
} |
public class MainActivity extends AppCompatActivity implements View.OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.btnReadJSON).setOnClickListener(this); findViewById(R.id.btnWriteJSON).setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.btnReadJSON: goReadJSON(); break; case R.id.btnWriteJSON: goWriteJSON(); break; } } private void goWriteJSON() { try { JSONObject root=new JSONObject(); root.put("cat","it"); // {"id":1,"ide":"Eclipse集成开发环境","name":"java语言"}, JSONObject lan1=new JSONObject(); lan1.put("id",1); lan1.put("ide","Eclipse基础开发环境"); lan1.put("name","Java语言"); // {"id":2,"ide":"Xcode","name":"Swift语言"}, JSONObject lan2=new JSONObject(); lan2.put("id",2); lan2.put("ide","Xcode"); lan2.put("name","Swift语言"); // {"id":3,"ide":"Visual Studio工作室","name":"C#语言"} JSONObject lan3=new JSONObject(); lan3.put("id",3); lan3.put("ide","Visual Studio工作室"); lan3.put("name","C#语言"); JSONArray array=new JSONArray(); array.put(lan1); array.put(lan2); array.put(lan3); root.put("languages",array); System.out.println(root.toString()); } catch (JSONException e) { e.printStackTrace(); } } private void goReadJSON() { 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); } br.close(); isr.close(); JSONObject root=new JSONObject(builder.toString()); System.out.println("cat="+root.getString("cat")); JSONArray array=root.getJSONArray("languages"); for (int i=0;i<array.length();i++){ 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(); } } }
|