JSON
来源:互联网 发布:淘宝全球直播是真的吗 编辑:程序博客网 时间:2024/05/16 01:28
JSON:JavaScript对象表示法,是存储和交换文本信息的语法。是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成。
JSON对象在花括号中书写,对象可以包含对个名称/值对,例:
{"firstName":"John","lastName":"Doe"}
JSON数组在方括号中书写,数组可包含多个对象,例:
{ //根部花括号表示一个整体的JSON数据 "employees":[ //employees对应一个JSON数组,数组中包含3个JSON对象 {"firstName":"John","lastName":"Doe"}, {"firstName":"Anna","lastName":"Smith"}, {"firstName":"Peter","lastName":"Jones"} ] }
在Android中创建JSON格式数据:
在MainActivity文件中:
try { //"cat":"it" 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(); //创建JSON数组包含lan1,lan2,lan3三个对象 array.put(lan1); array.put(lan2); array.put(lan3); root.put("languages", array); //将array添加到根元素中 System.out.println(root.toString()); } catch (JSONException e) { e.printStackTrace(); }输出结果:
{"languages":[{"id":1,"ide":"Eclipse","name":"Java"},{"id":2,"ide":"XCode","name":"Swift"},{"id":3,"ide":"Visual Studio","name":"C#"}],"cat":"it"}
在Android中读取JSON格式数据:
在Android中存在一个JSON格式数据,文件名为 text.json:
MainActivity中:
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")); //get+数据类型 ,cat为string类型数据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")); //id为整型System.out.println("name="+lan.getString("name"));System.out.println("ide="+lan.getString("ide"));}} catch (UnsupportedEncodingException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (JSONException e) {e.printStackTrace();}输出结果:
0 0
- Json
- JSON
- JSON
- JSON
- json
- JSON
- JSON
- json
- Json
- json
- JSON
- json
- json
- JSON
- json
- JSON
- JSON
- json
- x264重要结构体详细说明(2): x264_image_t、x264_picture_t、x264_nal_t
- TIPTOP ERP 调试debug时如何查看临时表中的数据
- libsvm 编译64位出错 svmtrain函数 "mxGetIr" 已过时
- 揭秘rand()函数
- ACE_Task介绍(生产者/消费者)
- JSON
- 买不到的数目 - 蓝桥杯
- 《C++编程》第二章第16题
- 杭电 HDU ACM 2049 不容易系列之(4)——考新郎
- [最小生成树] 蓝桥杯 城市建设
- 深入懒加载
- eclipse自动提示设置
- HDOJ 饭卡 2546
- windows下编译配置x264