JSON XML IO数据操作
一、XML解析
package org.hjw.service; import java.util.ArrayList;
import java.util.List; import org.hjw.model.Product;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler; public class XML2Product extends DefaultHandler {
private Product product;
private List<Product> products;
StringBuffer buffer = new StringBuffer(); public List<Product> getProducts() {
return products;
} @Override
public void characters(char[] ch, int start, int length)
throws SAXException {
buffer.append(ch, start, length);
super.characters(ch, start, length);
} @Override
public void startDocument() throws SAXException {
products = new ArrayList<Product>();
} @Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if (localName.equals("product")) {
product = new Product();
}
super.startElement(uri, localName, qName, attributes);
} @Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (localName.equals("product")) {
products.add(product);
} else if (localName.equals("id")) {
product.setId(Integer.parseInt(buffer.toString().trim()));
buffer.setLength(0);
} else if (localName.equals("name")) {
product.setName(buffer.toString().trim());
buffer.setLength(0);
} else if (localName.equals("price")) {
product.setPrice(Float.parseFloat(buffer.toString().trim()));
buffer.setLength(0);
}
super.endElement(uri, localName, qName);
} }
然后只需在主函数中:
InputStream is = getResources().openRawResource(R.raw.products);
XML2Product xml2Product = new XML2Product();
android.util.Xml.parse(is, Xml.Encoding.UTF_8, xml2Product);
List<Product> products = xml2Product.getProducts();
二、JSON解析
主要是通过JsonWriter类和JsonReader类实现读写功能。
writer.beginObject();
writer.name("id").value(product.id);//key-value对应
writer.name("name").value(product.name);
writer.endObject();
一般来说,我们要尽可能的分层次的解析,让代码实现更好的分离,流操作-数组操作-对象操作。
JsonReader--------具体的读操作:
reader.beginObject();
while (reader.hasNext())
{
String field = reader.nextName();//游标往后移 if (field.equals("id"))
{
id = reader.nextString();//获取数据
}
else if (field.equals("name"))
{
name = reader.nextString(); }
else
{
reader.skipValue();
}
}
reader.endObject();
一般来说,只要Reader初始化输入流,通过ArrayList接收,分层次的读取便可实现功能。
三、IO操作
public void onClick_SaveImageToSDCard(View view)
{
try
{
FileOutputStream fos = new FileOutputStream(
android.os.Environment.getExternalStorageDirectory()
+ "/image.jpg");//获取sd卡根目录
InputStream is = getResources().getAssets().open("image.jpg"); byte[] buffer = new byte[8192];
int count = 0;
while ((count = is.read(buffer)) >= 0)
{
fos.write(buffer, 0, count);//写文件
}
fos.close();
is.close();
Toast.makeText(this, "已成功将图像文件写到SD卡上.", Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
读文件:
public void onClick_ReadImageFromSDCard(View view)
{
String filename = android.os.Environment.getExternalStorageDirectory()
+ "/image.jpg"; if (!new File(filename).exists())
{
Toast.makeText(this, "还没有往SD卡写入图像文件", Toast.LENGTH_LONG).show();
return;
}
ImageView imageView = (ImageView) findViewById(R.id.imageview);
try
{
FileInputStream fis = new FileInputStream(filename);//初始化文件输入流
Bitmap bitmap = BitmapFactory.decodeStream(fis);
imageView.setImageBitmap(bitmap); fis.close();
}
catch (Exception e)
{ }
}
如果不用数据库的话,以上操作都能实现数据操作,不过更推荐xml文件读写,当然如果在网络应用中,用JSON是最好的轻量级选择。
JSON XML IO数据操作的更多相关文章
- XML文件数据操作
#region XML序列化文件和反序列化 /// <summary> /// 通用类的保存函数,可以将已经声明过可序列化的类以文件方式保存起来. /// 保存格式分为 XML明文式和 二 ...
- ASP.NET MVC WebApi 返回数据类型序列化控制(json,xml) 用javascript在客户端删除某一个cookie键值对 input点击链接另一个页面,各种操作。 C# 往线程里传参数的方法总结 TCP/IP 协议 用C#+Selenium+ChromeDriver 生成我的咕咚跑步路线地图 (转)值得学习百度开源70+项目
ASP.NET MVC WebApi 返回数据类型序列化控制(json,xml) 我们都知道在使用WebApi的时候Controller会自动将Action的返回值自动进行各种序列化处理(序列化为 ...
- json和xml封装数据、数据缓存到文件中
一.APP的通信格式之xml xml:扩展标记语言,可以用来标记数据,定义数据类型,是一种允许用户对自己标记语言进行定义的源语言.XML格式统一,扩平台语言,非常适合数据传输和通信,业界公认的标准. ...
- HttpClient获取返回类型为JSON或XML的数据
Java_HttpClient获取返回类型为JSON或XML的数据 原创 2017年04月06日 17:38:29 706 HttpClient 获取返回类型为JSON或XML的数据 使用httpco ...
- IO流总结---- 字节流 ,字符流, 序列化 ,数据操作流,打印流 , Properties 集合
笔记内容: 什么是流 字节流 字符流 序列化 数据操作流(操作基本数据类型的流)DataInputStream 打印流 Properties 集合 什么是流: 流是个抽象的概念,是对输入输出设备的抽象 ...
- python 发送json数据操作实例分析 - python
文章来源:嗨学网 敏而好学论坛www.piaodoo.com 欢迎大家相互学习 本文实例讲述了python 发送json数据操作.分享给大家供大家参考,具体如下: # !/usr/bin/env py ...
- Python常用的数据文件存储的4种格式(txt/json/csv/excel)及操作Excel相关的第三方库(xlrd/xlwt/pandas/openpyxl)(2021最新版)
序言:保存数据的方式各种各样,最简单的方式是直接保存为文本文件,如TXT.JSON.CSV等,除此之外Excel也是现在比较流行的存储格式,通过这篇文章你也将掌握通过一些第三方库(xlrd/xlwt/ ...
- (Unity)XML文件读写与IO文件操作类使用介绍
using System.Xml; //xml文件操作命名空间 #region 写入操作 void WriteXMLFile(string _fileName) { Xm ...
- php返回json,xml,JSONP等格式的数据
php返回json,xml,JSONP等格式的数据 返回json数据: header('Content-Type:application/json; charset=utf-8'); $arr = a ...
随机推荐
- MATLAB - 为什么imshow(g,[])可以正常显示,而imshow(g)却显示空白图像?
Q:为什么imshow(g,[])可以正常显示,而imshow(g)却显示空白图像? A:数据类型如果是double,imshow的处理范围是0-1数据类型如果是uint8,imshow的处理范围是0 ...
- ADO.NET知识的运用一(Day 26)
哈哈,又到了总结的时间了,来回顾一下今天主要学了关于ADO.NET的哪些知识吧.(这次学的ADO访问数据库主要以访问SQL数据库为主) 理论: 首先我们要知道为什么要学习ADO.NET? 因为我们之 ...
- [Jobdu] 题目1367:二叉搜索树的后序遍历序列
题目描述: 输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果.如果是则输出Yes,否则输出No.假设输入的数组的任意两个数字都互不相同. 输入: 每个测试案例包括2行: 第一行为1个整数 ...
- BZOJ 2301 Problem b(莫比乌斯反演+分块优化)
题目链接:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=37166 题意:对于给出的n个询问,每次求有多少个数对(x,y),满 ...
- mac上搭建svn服务器
1.terminal 执行svnadmin create 库地址/库名,生成的即为svn库根地址. 2.修改对应目录下conf/svnserve.conf文件: anon-access = read ...
- COB封装的优势
随着固态照明技术的不断进步,COB(chip-on-board)封装技术得到越来越多的重视,由于COB光源有热阻低,光通量密度高,眩光少,发光均匀等特性,在室内外照明灯具中得到了广泛的应用,如筒灯,球 ...
- golang ODBC 访问access数据库(问题解决之心理路程)
最近项目需要,需要操作access,以前是用VC++ OLE访问,网络用ACE库,感觉很庞大...决定用go试试 网上用的最多的就是这个https://github.com/weigj/go-odbc ...
- ThinkPHP 3.1.2 查询方式的一般使用1
public function show(){ echo "访问了index模块下的show方法!!"; echo "欢迎你".$_GET['name'].'你 ...
- Shared_from_this 几个值得注意的地方
shared_from_this()是enable_shared_from_this<T>的成员 函数,返回shared_ptr<T>.首先需要注意的是,这个函数仅在share ...
- uva11536 Smallest Sub-Array
Thinking about it: 我的思路跟sliding window有点类似.假设已经确定了一个区间[l, r],序列中从 l 到 r 恰好包含了[1, K]的各个元素,则从 r 开始继续迭代 ...