比起XML文件解析,JSON数据解析的有点在于他的体积小,在网络上传输的时候可以更省流量。同时它也有缺点,Json数据的语义性较差,看起来没有XML直观。现在JSON已经被大多数开发人员所接受,在网络数据的传输当中应用非常广泛。现在做的项目需要把数据转换成下面的格式:

 {"PatitentData":[{"patient_mhistory":"高血压","patient_insomnia":"六个月","patient_gender":"男","patient_name":"张三","current_date":"2015.4.10","patient_phone":"1243543546","patient_scde":"大学本科","patient_age":"56","patient_postion":"农民"}],"sleepDiary":[{"day07":"1243535","day06":"12324343","day05":"1243434","day04":"2435434521","day01":"121422343","day02":"1231421454","day03":"1243243"}],"testData":[{"isi":"12324324","hama":"122543543","hamd":"2334255","sleepness":"1243345432","pqsi":"124332144452"}]}

首先建立 PatientInformation.java、PatientTest.java和SleepDiary这三个类,主要是用来封装一些信息

PatientInformation.java

package com.zghaikun.json;public class PatientInformation {private int id;private String patient_name;private String patient_gender;private String patient_age;private String patient_postion;private String patient_scde;private String patient_insomnia;private String patient_mhistory;private String patient_phone;private String current_date;private int patient_hamd;public PatientInformation() {super();}public PatientInformation(int patient_hamd) {super();this.patient_hamd = patient_hamd;}public PatientInformation( String current_date,String patient_name, String patient_gender,String patient_age, String patient_postion, String patient_scde,String patient_insomnia, String patient_mhistory,String patient_phone) {super();this.current_date = current_date;this.patient_name = patient_name;this.patient_gender = patient_gender;this.patient_age = patient_age;this.patient_postion = patient_postion;this.patient_scde = patient_scde;this.patient_insomnia = patient_insomnia;this.patient_mhistory = patient_mhistory;this.patient_phone = patient_phone;}public PatientInformation(int id, String current_date,String patient_name, String patient_gender,String patient_age, String patient_postion, String patient_scde,String patient_insomnia, String patient_mhistory,String patient_phone) {super();this.id = id;this.current_date = current_date;this.patient_name = patient_name;this.patient_gender = patient_gender;this.patient_age = patient_age;this.patient_postion = patient_postion;this.patient_scde = patient_scde;this.patient_insomnia = patient_insomnia;this.patient_mhistory = patient_mhistory;this.patient_phone = patient_phone;}public int getPatient_hamd() {return patient_hamd;}public void setPatient_hamd(int patient_hamd) {this.patient_hamd = patient_hamd;}public String getPatient_age() {return patient_age;}public void setPatient_age(String patient_age) {this.patient_age = patient_age;}public String getCurrentdate() {return current_date;}public void setCurrentdate(String currentdate) {this.current_date = currentdate;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getPatient_name() {return patient_name;}public void setPatient_name(String patient_name) {this.patient_name = patient_name;}public String getPatient_gender() {return patient_gender;}public void setPatient_gender(String patient_gender) {this.patient_gender = patient_gender;}public String getPatient_postion() {return patient_postion;}public void setPatient_postion(String patient_postion) {this.patient_postion = patient_postion;}public String getPatient_scde() {return patient_scde;}public void setPatient_scde(String patient_scde) {this.patient_scde = patient_scde;}public String getPatient_insomnia() {return patient_insomnia;}public void setPatient_insomnia(String patient_insomnia) {this.patient_insomnia = patient_insomnia;}public String getPatient_mhistory() {return patient_mhistory;}public void setPatient_mhistory(String patient_mhistory) {this.patient_mhistory = patient_mhistory;}public String getPatient_phone() {return patient_phone;}public void setPatient_phone(String patient_phone) {this.patient_phone = patient_phone;}
}

PatientTest.java

package com.zghaikun.json;public class PatientTest {int id;String pqsi;String sleepness;String hama;String hamd;String isi;public String getIsi() {return isi;}public void setIsi(String isi) {this.isi = isi;}public PatientTest() {super();}public PatientTest(int id, String pqsi, String sleepness, String hama,String hamd,String isi) {super();this.id = id;this.pqsi = pqsi;this.sleepness = sleepness;this.hama = hama;this.hamd = hamd;this.isi = isi;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getPqsi() {return pqsi;}public void setPqsi(String pqsi) {this.pqsi = pqsi;}public String getSleepness() {return sleepness;}public void setSleepness(String sleepness) {this.sleepness = sleepness;}public String getHama() {return hama;}public void setHama(String hama) {this.hama = hama;}public String getHamd() {return hamd;}public void setHamd(String hamd) {this.hamd = hamd;}}

SleepDiary.java

package com.zghaikun.json;public class SleepDiary {private int id;private String day01;private String day02;private String day03;private String day04;private String day05;private String day06;private String day07;public SleepDiary(String day01, String day02, String day03, String day04,String day05, String day06, String day07) {super();this.day01 = day01;this.day02 = day02;this.day03 = day03;this.day04 = day04;this.day05 = day05;this.day06 = day06;this.day07 = day07;}public SleepDiary(int id, String day01, String day02, String day03,String day04, String day05, String day06, String day07) {super();this.id = id;this.day01 = day01;this.day02 = day02;this.day03 = day03;this.day04 = day04;this.day05 = day05;this.day06 = day06;this.day07 = day07;}public SleepDiary() {super();}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getDay01() {return day01;}public void setDay01(String day01) {this.day01 = day01;}public String getDay02() {return day02;}public void setDay02(String day02) {this.day02 = day02;}public String getDay03() {return day03;}public void setDay03(String day03) {this.day03 = day03;}public String getDay04() {return day04;}public void setDay04(String day04) {this.day04 = day04;}public String getDay05() {return day05;}public void setDay05(String day05) {this.day05 = day05;}public String getDay06() {return day06;}public void setDay06(String day06) {this.day06 = day06;}public String getDay07() {return day07;}public void setDay07(String day07) {this.day07 = day07;}}

一个布局文件,由两个按键和一个textView组成,
activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><Buttonandroid:id="@+id/bt2" android:layout_width="match_parent"android:layout_height="wrap_content"android:text="把普通数据换成json数据格式的string"/><Buttonandroid:id="@+id/bt4" android:layout_width="match_parent"android:layout_height="wrap_content"android:text="解析带集合的json字符串"/><TextViewandroid:id="@+id/text"android:layout_width="wrap_content"android:layout_height="wrap_content"android:gravity="center"android:textSize="30sp"android:text="@string/hello_world" /></LinearLayout>

Mainactivity.java

package com.zghaikun.json;import java.util.ArrayList;
import java.util.List;import org.apache.axis2.AxisFault;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;public class MainActivity extends Activity implements OnClickListener {private Button button1, button2, button3, button4;  //4个按钮private TextView textView;  //显示处理结果的textviewprivate List<PatientInformation> patientInfos; //保存数据的集合private List<PatientTest> patientTest;private List<SleepDiary> sleepDiarys;private JSONObject object;  //JSONObject对象,处理一个一个的对象private JSONObject objPatientInfo;private JSONObject objTestData;private JSONObject objSleepDiary;private JSONArray jsonArrayPatientInfo;//JSONObject对象,处理一个一个集合或者数组private JSONArray jsonArrayTestData;//JSONObject对象,处理一个一个集合或者数组private JSONArray jsonArraySleepDiary;//JSONObject对象,处理一个一个集合或者数组private String jsonString;  //保存带集合的json字符串private String jsonString2;//不带集合的json字符串@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initView(); //初始化控件initDate(); //初始化数据setListener(); //绑定监事件//       try {
//          SimpleServiceStub stub  = new SimpleServiceStub();
//          SimpleServiceStub.GetGreeting gg = new SimpleServiceStub.GetGreeting();
//          gg.setParam0("比尔");
//          System.out.println(stub.getGreeting(gg).local_return);
//          System.out.println(stub.getPrice().local_return);
//      } catch (Exception e) {
//          // TODO Auto-generated catch block
//          e.printStackTrace();
//      }}private void initView() {// TODO Auto-generated method stubbutton2 = (Button) findViewById(R.id.bt2);button4 = (Button) findViewById(R.id.bt4);textView = (TextView) findViewById(R.id.text);}private void initDate() {//设置了两个对象 patientInfos = new ArrayList<PatientInformation>();PatientInformation pateintInfo = new PatientInformation();pateintInfo.setPatient_name("张三");pateintInfo.setPatient_gender("男");pateintInfo.setPatient_age("56");pateintInfo.setPatient_postion("农民");pateintInfo.setPatient_scde("大学本科");pateintInfo.setPatient_insomnia("六个月");pateintInfo.setPatient_mhistory("高血压");pateintInfo.setPatient_phone("1243543546");pateintInfo.setCurrentdate("2015.4.10");patientInfos.add(pateintInfo);//测试数据patientTest = new ArrayList<PatientTest>();PatientTest PatienData = new PatientTest();PatienData.setPqsi("124332144452");PatienData.setSleepness("1243345432");PatienData.setHama("122543543");PatienData.setHamd("2334255");PatienData.setIsi("12324324");patientTest.add(PatienData);sleepDiarys = new ArrayList<SleepDiary>();SleepDiary sleepDiary = new SleepDiary();sleepDiary.setDay01("121422343");sleepDiary.setDay02("1231421454");sleepDiary.setDay03("1243243");sleepDiary.setDay04("2435434521");sleepDiary.setDay05("1243434");sleepDiary.setDay06("12324343");sleepDiary.setDay07("1243535");sleepDiarys.add(sleepDiary);}
//  //绑定监听器private void setListener() {button2.setOnClickListener(this);button4.setOnClickListener(this);}//把一个集合转换成json格式的字符串private void changeArrayDateToJson() { jsonArrayPatientInfo = null;object = null;jsonArrayPatientInfo = new JSONArray();jsonArrayTestData = new JSONArray();jsonArraySleepDiary = new JSONArray();object = new JSONObject();//遍历上面初始化的集合数据,把数据加入JSONObject里面for (int i = 0; i < patientInfos.size(); i++) {  //一个user对象,使用一个JSONObject对象来装objPatientInfo = new JSONObject();try {//从集合取出数据,放入JSONObject里面 JSONObject对象和map差不多用法,以键和值形式存储数据objPatientInfo.put("patient_name", patientInfos.get(i).getPatient_name()); objPatientInfo.put("patient_gender", patientInfos.get(i).getPatient_gender());objPatientInfo.put("patient_age", patientInfos.get(i).getPatient_age());objPatientInfo.put("patient_postion", patientInfos.get(i).getPatient_postion());objPatientInfo.put("patient_scde", patientInfos.get(i).getPatient_scde());objPatientInfo.put("patient_insomnia", patientInfos.get(i).getPatient_insomnia());objPatientInfo.put("patient_mhistory", patientInfos.get(i).getPatient_mhistory());objPatientInfo.put("patient_phone", patientInfos.get(i).getPatient_phone());objPatientInfo.put("current_date", patientInfos.get(i).getCurrentdate());//把JSONObject对象装入jsonArray数组里面jsonArrayPatientInfo.put(objPatientInfo); } catch (JSONException e) {e.printStackTrace();}}for(int i = 0 ; i < patientTest.size(); i++){//测试对象,使用JSONObjectobjTestData = new JSONObject();try {objTestData.put("pqsi", patientTest.get(i).getPqsi());objTestData.put("sleepness", patientTest.get(i).getSleepness());objTestData.put("hama", patientTest.get(i).getHama());objTestData.put("hamd", patientTest.get(i).getHamd());objTestData.put("isi", patientTest.get(i).getIsi());//把JSONObject对象装入jsonArray数组里面jsonArrayTestData.put(objTestData);} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();}}for(int i = 0 ; i < sleepDiarys.size(); i++){//测试对象,使用JSONObjectobjSleepDiary = new JSONObject();try {objSleepDiary.put("day01", sleepDiarys.get(i).getDay01());objSleepDiary.put("day02", sleepDiarys.get(i).getDay02());objSleepDiary.put("day03", sleepDiarys.get(i).getDay03());objSleepDiary.put("day04", sleepDiarys.get(i).getDay04());objSleepDiary.put("day05", sleepDiarys.get(i).getDay05());objSleepDiary.put("day06", sleepDiarys.get(i).getDay06());objSleepDiary.put("day07", sleepDiarys.get(i).getDay07());//把JSONObject对象装入jsonArray数组里面jsonArraySleepDiary.put(objSleepDiary);} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();}}try {//再把JSONArray数据加入JSONObject对象里面(数组也是对象)object.put("PatitentData", jsonArrayPatientInfo);object.put("testData", jsonArrayTestData);object.put("sleepDiary", jsonArraySleepDiary);//object.put("time", "2013-11-14"); //这里还可以加入数据,这样json型字符串,就既有集合,又有普通数据} catch (JSONException e) {e.printStackTrace();}jsonString = null;//把JSONObject转换成json格式的字符串jsonString  = object.toString(); textView.setText(jsonString);Log.i("输出json字符串", "转换成json字符串: " + jsonString);}@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.bt2:changeArrayDateToJson(); //点击第2个按钮,把普通数据换成json数据格式的stringbreak;case R.id.bt4://解析带集合的json字符串if (jsonString==null || "".equals(jsonString)) {Toast.makeText(MainActivity.this, "请先点击第2按钮把数据换成json字符串", Toast.LENGTH_LONG).show();return;}changeJsonToData1();break;default:break;}}//解析带集合的json字符串private void changeJsonToData1(){//用来保存解析出来的数据,显示在textviewStringBuilder stringBuilder = new StringBuilder(); StringBuilder stringBuilder2 = new StringBuilder(); StringBuilder stringBuilder3 = new StringBuilder(); PatientInformation patient;PatientTest patientTest;SleepDiary sleepDiary;List<PatientInformation> pInfoList=new ArrayList<PatientInformation>();List<PatientTest> pTestList = new ArrayList<PatientTest>();List<SleepDiary> sleepList = new ArrayList<SleepDiary>();try {object = new JSONObject(jsonString); jsonArrayPatientInfo = object.getJSONArray("PatitentData");  //通过key,获取JSONObject里面的一个JSONArray数组jsonArrayTestData = object.getJSONArray("testData");jsonArraySleepDiary = object.getJSONArray("sleepDiary");for (int i = 0; i < jsonArrayPatientInfo.length(); i++) {  //遍历数据object = jsonArrayPatientInfo.getJSONObject(i); //从JSONArray里面获取一个JSONObject对象patient = new PatientInformation();patient.setPatient_name(object.getString("patient_name"));patient.setPatient_gender(object.getString("patient_gender"));patient.setPatient_age(object.getString("patient_age"));patient.setPatient_postion(object.getString("patient_postion"));patient.setPatient_scde(object.getString("patient_scde"));patient.setPatient_insomnia(object.getString("patient_insomnia"));patient.setPatient_mhistory(object.getString("patient_mhistory"));patient.setPatient_phone(object.getString("patient_phone"));patient.setCurrentdate(object.getString("current_date"));pInfoList.add(patient);}} catch (JSONException e) {e.printStackTrace();}for (int i = 0; i < pInfoList.size(); i++) {stringBuilder.append("患者姓名:"+pInfoList.get(i).getPatient_name()).append("   ").append("患者年龄:" + pInfoList.get(i).getPatient_age()).append("   ").append("性别:" + pInfoList.get(i).getPatient_gender()).append("    ").append("职业:" + pInfoList.get(i).getPatient_postion()).append("   ").append("学历:" + pInfoList.get(i).getPatient_scde()).append("  ").append("失眠时间:" + pInfoList.get(i).getPatient_insomnia()).append("   ").append("既往病史: " + pInfoList.get(i).getPatient_mhistory()).append("   ").append("联系方式:" + pInfoList.get(i).getPatient_phone()).append("   ").append("测试时间 :" + pInfoList.get(i).getCurrentdate());}for(int i = 0;i < jsonArrayTestData.length();i++){try {object = jsonArrayTestData.getJSONObject(i);patientTest = new PatientTest();patientTest.setPqsi(object.getString("pqsi"));patientTest.setSleepness(object.getString("sleepness"));patientTest.setHama(object.getString("hama"));patientTest.setHamd(object.getString("hamd"));patientTest.setIsi(object.getString("isi"));pTestList.add(patientTest);} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();} }for (int i = 0; i < pTestList.size(); i++) {stringBuilder2.append("pqsi:"+pTestList.get(i).getPqsi()).append("   ").append("sleepness:" + pTestList.get(i).getSleepness()).append("   ").append("hama" + pTestList.get(i).getHama()).append("    ").append("hamd:" + pTestList.get(i).getHamd()).append("   ").append("isi:" + pTestList.get(i).getIsi());}System.out.println("111111111111111111111111111");for(int i = 0;i < jsonArraySleepDiary.length();i++){try {object = jsonArraySleepDiary.getJSONObject(i);System.out.println("22222222" + object);sleepDiary = new SleepDiary();sleepDiary.setDay01(object.getString("day01"));sleepDiary.setDay02(object.getString("day02"));sleepDiary.setDay03(object.getString("day03"));sleepDiary.setDay04(object.getString("day04"));sleepDiary.setDay05(object.getString("day05"));sleepDiary.setDay06(object.getString("day06"));sleepDiary.setDay07(object.getString("day07"));sleepList.add(sleepDiary);System.out.println("2222222222222222222222222");} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();} }for (int i = 0; i < sleepList.size(); i++) {stringBuilder3.append("day01:"+sleepList.get(i).getDay01()).append("   ").append("day02:" + sleepList.get(i).getDay02()).append("   ").append("day03" + sleepList.get(i).getDay03()).append("    ").append("day04:" + sleepList.get(i).getDay04()).append("   ").append("day05:" + sleepList.get(i).getDay05()).append("   ").append("day06:" + sleepList.get(i).getDay06()).append("   ").append("day07:" + sleepList.get(i).getDay07());}textView.setText(stringBuilder.toString() + "\n" + stringBuilder2.toString() + "\n" + stringBuilder3);}
}

程序中先通过initDate()方法设置数据,再通过changeArrayDateToJson()函数将数据转换成json数据格式,转换后再通过changeJsonToData1()方法吧json数据转换成普通的数据,然后在进行下一步的操作。

android 将数据转换成JSON数据格式并使用JSONObject解析JSON格式的数据相关推荐

  1. 后台返回的数组包对象格式的数据转换成表格数据格式的方法

    后台返回的数组包对象格式的数据转换成表格数据格式的方法 transformDate(res) {const mapInfo = {id: '编号',password: '密码',mobile: '手机 ...

  2. 【Android】 Gson的引用 / 插件GsonFormat / 使用 / GsonFormat解析Json的方法和使用

    一.Gson的引入 方法一 File -> Project Structure -> Dependencies -> Library Dependency -> 在搜索框中输入 ...

  3. c语言json结构体_C语言解析JSON源码

    2020-01-09 关键字:cJSON.linux JSON解析 JSON 是一种在互联网领域内很常用的轻量级数据交换协议. 它与 XML 的地位差不多,但就笔者而言,笔者更喜欢 JSON 的风格, ...

  4. sql解析json oracle,oracle 11g plsql解析json数据示例1

    以下存储过程将数据库表中的clob类型字段(存储的内容为对应Json格式数据)读取出来,对其解析,进行相关业务操作 CREATE OR REPLACE PROCEDURE xq_midso_gen(p ...

  5. ajax请求解析json,如何为Ajax请求解析json响应?

    我是ajax/javascript的新手.我试图解析响应下面Ajax请求:如何为Ajax请求解析json响应? function invokeMediationRestService(rql) { v ...

  6. Oracle怎么获取json类型字符串值,sql解析json格式字段 如何获取json中某个字段的值?...

    java将json数据解析为sql语句?小编给你倒一杯热水.可你惦记着其他饮料,所以你将它放置一旁.等你想起那杯水时,可惜它已经变得冰冷刺骨. 图片中是json数据,每个数据的开头都有表名称,操作类型 ...

  7. jsonobject解析json字符串

    首先 参考上一篇文章JSONObject详解 解析字符串,有简单的也有复杂的 下面是一段简单的json数据 这其实就是jsonobject {"code": 1,"dev ...

  8. python 解析json typeerror_TypeError:在使用Python解析JSON时,字符串索引必须是整数?...

    问题是jsonStr是一个字符串,它用JSON编码一些对象,而不是实际的对象. 显然,你知道这是一个字符串,因为你称它为jsonStr.事实证明这条线是有效的:jsonStr = data.decod ...

  9. php curl get utf 8,curl get获取到一个utf-8 json字符串,用json_decode解析说格式不对。...

    $ch = curl_init();//初始化curl curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_RETURNTRANSFE ...

最新文章

  1. 【 FPGA/IC 】常考加法器总结
  2. 分布式系统唯一ID生成方案汇总
  3. ubuntu解决eclipse中logcat只显示level栏
  4. Ubuntu 配置Samba 服务器
  5. gridview選發行彈出層 模板列
  6. 实用干货:电放提单详解,与海运单、一般提单到底有什么区别?
  7. HEVC中的样点自适应补偿——Sample Adaptive Offset (SAO)
  8. WiFi转串口 以太网模块
  9. python暑假培训成都
  10. java模拟交通信号灯_java 多线程交通信号灯模拟过程详解
  11. 在CMD下使用sc命令,报openservice failed 1060错误
  12. php http 缓存,HTTP 缓存中的 Vary
  13. 大学本科毕业论文查重有什么要求?
  14. 如何在linux下运行python程序
  15. 计算机科学技术考研内容,计算机科学与技术考研考什么 具体内容有哪些
  16. 超详细excle入门教程!万字长文,图文详解!
  17. 编程之类的文案_有哪些让人眼前一亮的广告文案?
  18. 解决QQ分享屏幕对方无法听到电脑系统声音的问题
  19. 精选蓝桥杯省赛基础题解2015-2022
  20. Python用selenium实现自动登录和下单的脚本

热门文章

  1. Ubuntu平台 Qt 5.x 安装方法
  2. Tinux 3.0 内存对齐算法
  3. 乐鑫代理-启明云端分享ESP32系列教程之二:Linux搭建esp-idf环境
  4. linux同步硬件和系统时钟,liunx系统下时钟不同步会出现问题 怎么同步Linux 的系统时钟和硬件时钟?...
  5. python调研报告总结体会_学习调研心得体会
  6. 低电压瞬态抑制二极管,有哪些常用的型号?
  7. MT7628/MT7688 修改串口2作为调试串口 所踩的坑
  8. linux切换图片的代码,cacaview – Linux终端下将图片转换ASCII Art代码图案
  9. pci-e串口卡linux 驱动下载,万能PCI串口卡驱动下载
  10. android object数组赋值_VUE2.X为什么只对数组的部分方法实现了数据监测?