public class GsonActivity extends Activity { Button saveButton; Button loadButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.gsonlayout); initControls(); } protected void initControls(){ saveButton = (Button) findViewById(R.id.btSave); loadButton = (Button) findViewById(R.id.btGsonLoad); saveButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { List<StudentInfo> studentInfos = new LinkedList<StudentInfo>() ; StudentInfo s1 = new StudentInfo(); s1.setId(1); s1.setName("张三"); s1.setAddress("武汉市"); s1.setPhone("12345671"); studentInfos.add(s1); StudentInfo s2 = new StudentInfo(); s2.setId(2); s2.setName("李四"); s2.setAddress("华工"); s2.setPhone("12345672"); studentInfos.add(s2); Gson gson = new Gson(); String json = gson.toJson(studentInfos); try { FileOutputStream fs = openFileOutput("gsonconfig.xml", MODE_PRIVATE); fs.write(json.getBytes()); fs.close(); Toast.makeText(GsonActivity.this, json, Toast.LENGTH_SHORT).show(); } catch (Exception e) { Toast.makeText(GsonActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); e.printStackTrace(); } } }); loadButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { List<StudentInfo> studentInfos = new LinkedList<StudentInfo>(); String json = ""; try { FileInputStream fileInputStream = openFileInput("gsonconfig.xml"); InputStreamReader inputStreamReader =new InputStreamReader(fileInputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); json = bufferedReader.readLine(); bufferedReader.close(); Gson gson = new Gson(); studentInfos = gson.fromJson(json, new TypeToken<List<StudentInfo>>() { }.getType()); for (StudentInfo studentInfo : studentInfos) { Toast.makeText(GsonActivity.this, studentInfo.toString(), Toast.LENGTH_SHORT).show(); } } catch (Exception e) { e.printStackTrace(); } } }); } }
gosn 解析
最新推荐文章于 2023-08-02 17:31:58 发布