安卓本地保存json文件系统中 .json是什么文件

android中JSON数据的读写方法 - 见证我的成长 - ITeye技术网站
博客分类:
[/color]用习惯了XML,总觉得JSON可读性又差,也不好保存等等,到真正接触了,才发现在android上,JSON就像亲儿子一样容易管教。
还是先看数据源,数据源我采用的是一系列的村民集合,村民的属性如下。
public class Folk {
引用
先看写数据,数据是我假定一个村的数据,由一个arraylist填装。通过一个for循环很容易取出了arraylist中的每个对象以及其数据,每个对象,即村民都可以生成一个JSONobject,这里json和java面向对象的思想是多么吻合。prey load!
其次还有一个JSONarray对象,就是一个JSON自己的Arraylist。好比我们把自己的对象转存到一个Json对象中,从我们的Arraylist中取出来,再装进一个Json的Arraylist。好比我把一个个村名从一辆大卡车上接下来(从自己的ArrayList取),把他们穿戴整齐了(装进Json对象中),再挥挥手把他们送上火星游的太空飞船(jsonArray),临走我在飞船上挂上了village的标签,火星上的同事会知道我的村民坐的是哪艘船。所有工序完成。
public class MyJsonWriter {
ArrayList&Folk&
File saveF
public MyJsonWriter(ArrayList&Folk& folks){
this.folks=
public void setFilePath(String filepath){
saveFile=new File(filepath);
saveFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
public String getJsonData(){
String jsonData =
String jsonData=new JSONStringer().object().key("village").value("abc").endObject().toString();
StringBuilder builder=new StringBuilder();
ArrayList&String& folksData=new ArrayList&String&();
JSONArray array=new JSONArray();
for(int i=0;i&folks.size();i++){
Folk folk=folks.get(i);
JSONObject jsonObject=new JSONObject();
jsonObject.put("name", folk.getName());
jsonObject.put("sex", folk.isSex()?"male":"female");
jsonObject.put("age", folk.getAge());
jsonObject.put("career", folk.getCareer());
jsonObject.put("salary", folk.getSalary());
folksData.add(jsonObject.toString());
array.put(jsonObject);
JSONArray jsonArray=new JSONArray(folksData);
int len = array.length();
jsonData=new JSONStringer().object().key("vallage").value(array).endObject().toString();
System.out.println(jsonData);
writeData(jsonData);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return jsonD
private void writeData(String jsonData) {
// TODO Auto-generated method stub
BufferedReader reader=new BufferedReader(new StringReader(jsonData));
BufferedWriter writer=new BufferedWriter(new FileWriter(saveFile));
int len=0;
char[] buffer=new char[1024];
while((len=reader.read(buffer))!=-1){
writer.write(buffer, 0, len);
writer.flush();
writer.close();
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
引用
愉快的时间总是过的特别快,村民们要回家了。这时候来了一辆宇宙飞船,上面挂着我临走时贴上的标签,看来是相亲门回家了。(得到了JSONarray的对象)。打开舱门,乡亲们陆陆续续的走了下来,我为每个人做了次详细的检查,保证不会让奇怪的生物混进来,乡亲们神清气爽的重回地球表面。(循环中取出JSONArray中的JSON对象,并装填到我们自己的对象中,并存入arraylist)
public class MyJsonReader {
String jsonD
// ArrayList&Folk&
public MyJsonReader(String jsonData){
this.jsonData=jsonD
public ArrayList&Folk& getJsonData(){
ArrayList&Folk& folks=new ArrayList&Folk&();
JSONObject jsonObject=new JSONObject(jsonData);
JSONArray jsonArray=jsonObject.getJSONArray("vallage");
int len = jsonArray.length();
for(int i=0;i&jsonArray.length();i++){
JSONObject json=jsonArray.getJSONObject(i);
Folk folk=new Folk();
folk.setName(json.optString("name"));
folk.setAge(json.optString("age"));
folk.setCareer(json.optString("career"));
folk.setSalary(json.optInt("salary"));
folk.setSex(json.optString("sex").equals("male")?true:false);
folks.add(folk);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
JSON的读写在android很简单,出奇的简单,让我这个准备花一个周五下午的人后面变得十分蛋疼的来写日志。
总的来说还有些小地方需要注意
JSONArray中添加json对象的方法不是用的add而是put
jsonData=new JSONStringer().object().key("vallage").value(array).endObject().toString();
.object和endObject成对出现 这很像XML写里面的starttag和endtag
最后我将一些的村民数据做为了一个village json对象的value,真的把这个Json对象幻想成了一艘宇宙飞船。。。
下载次数: 195
浏览 15725
浏览: 289395 次
来自: 武汉
我每次走到movie.draw(canvas,0, 0);
徐颖慧 写道为什么打不开啊?额 果然打不开了。。
为什么打不开啊?
为什么打不开啊
很好!易懂温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!&&|&&
LOFTER精选
网易考拉推荐
用微信&&“扫一扫”
将文章分享到朋友圈。
用易信&&“扫一扫”
将文章分享到朋友圈。
服务器端://解码Bitmap bm&=&BitmapFactory.decodeFile("/path/to/image.jpg");&baos&=&new&();bm.compress(Bitmap.CompressFormat.JPEG,&100, baos);&//bm is the bitmap objectbyte[]&b&=&baos.toByteArray();
用微信&&“扫一扫”
将文章分享到朋友圈。
用易信&&“扫一扫”
将文章分享到朋友圈。
历史上的今天
在LOFTER的更多文章
loftPermalink:'',
id:'fks_',
blogTitle:'Android、iOS等手机客户端如何使用JSON方式上传文件或图片',
blogAbstract:'在开发Android、iOS等移动应用时经常需要以JSON的方式向服务器传输图片或者文字。如何实现呢,常见的方法是将图片或文件转换为字符串,如二进制的01字符串进,行传输,当服务器接收到字符串后对其进行解析,并将其保存为图像或者文件。在具体实现时,可以很方便地使用Base64进行编码;同时人性化的一些应用在上传图像时经常会在手机客户端提供图像裁剪的功能,这时可以对原始图片进行压缩和裁剪,之后对新的图片进行编码,从而提供了压缩并满足用户裁剪的需求。',
blogTag:'',
blogUrl:'blog/static/',
isPublished:1,
istop:false,
modifyTime:0,
publishTime:9,
permalink:'blog/static/',
commentCount:0,
mainCommentCount:0,
recommendCount:0,
bsrk:-100,
publisherId:0,
recomBlogHome:false,
currentRecomBlog:false,
attachmentsFileIds:[],
groupInfo:{},
friendstatus:'none',
followstatus:'unFollow',
pubSucc:'',
visitorProvince:'',
visitorCity:'',
visitorNewUser:false,
postAddInfo:{},
mset:'000',
remindgoodnightblog:false,
isBlackVisitor:false,
isShowYodaoAd:false,
hostIntro:'',
hmcon:'0',
selfRecomBlogCount:'0',
lofter_single:''
{list a as x}
{if x.moveFrom=='wap'}
{elseif x.moveFrom=='iphone'}
{elseif x.moveFrom=='android'}
{elseif x.moveFrom=='mobile'}
${a.selfIntro|escape}{if great260}${suplement}{/if}
{list a as x}
推荐过这篇日志的人:
{list a as x}
{if !!b&&b.length>0}
他们还推荐了:
{list b as y}
转载记录:
{list d as x}
{list a as x}
{list a as x}
{list a as x}
{list a as x}
{if x_index>4}{break}{/if}
${fn2(x.publishTime,'yyyy-MM-dd HH:mm:ss')}
{list a as x}
{if !!(blogDetail.preBlogPermalink)}
{if !!(blogDetail.nextBlogPermalink)}
{list a as x}
{if defined('newslist')&&newslist.length>0}
{list newslist as x}
{if x_index>7}{break}{/if}
{list a as x}
{var first_option =}
{list x.voteDetailList as voteToOption}
{if voteToOption==1}
{if first_option==false},{/if}&&“${b[voteToOption_index]}”&&
{if (x.role!="-1") },“我是${c[x.role]}”&&{/if}
&&&&&&&&${fn1(x.voteTime)}
{if x.userName==''}{/if}
网易公司版权所有&&
{list x.l as y}
{if defined('wl')}
{list wl as x}{/list}Android中生成、使用Json数据实例-爱编程
Android中生成、使用Json数据实例
1、Json的制作
复制代码 代码如下:
package com.example.usingjson2;&
import org.json.JSONE&
import org.json.JSONO&
import android.os.B&
import android.app.A&
public class MainActivity extends Activity {&
&&& @Override&
&&& protected void onCreate(Bundle savedInstanceState) {&
&&&&&&& super.onCreate(savedInstanceState);&
&&&&&&& setContentView(R.layout.activity_main);&
&&&&&&& System.out.println("\"Hello World\"");&
&&&&&&& JSONObject object = new JSONObject();&
&&&&&&& try {&
&&&&&&&&&&& object.put("one", "yu");&
&&&&&&&&&&& object.put("two", "xi");&
&&&&&&&&&&& object.put("three", "kuo");&
&&&&&&&&&&& object.put("four", "hi");&
&&&&&&&&&&& System.out.println(object);&
&&&&&&&&&&&&&
&&&&&&& } catch (JSONException e) {&
&&&&&&&&&&& // TODO Auto-generated catch block&
&&&&&&&&&&& e.printStackTrace();&
&&&&&&& }&
2、Json的使用
(1)首先在当前包中创建新的class
复制代码 代码如下:
package com.example.
public class Data {
&public static final String jsonStr = "{'arr':[1,2,3,4],'dat':[yu,xi,kuo]}";
(2)在Activity中调用
复制代码 代码如下:
package com.example.
import org.json.JSONA
import org.json.JSONE
import org.json.JSONO
import android.os.B
import android.app.A
public class MainActivity extends Activity {
&@Override
&protected void onCreate(Bundle savedInstanceState) {
&&super.onCreate(savedInstanceState);
&&setContentView(R.layout.activity_main);
&&System.out.println(Data.jsonStr);
&&&JSONObject jsonObject = new JSONObject(Data.jsonStr);
&&&JSONArray jsonArray = jsonObject.getJSONArray("arr");
&&&System.out.println(jsonArray);
&&&for(int i = 0; i & jsonArray.length(); i++)
&&&&System.out.println(jsonArray.get(i));
&&&JSONArray jsonArray2 = jsonObject.getJSONArray("dat");
&&&System.out.println(jsonArray2);
&&&for(int j = 0; j & jsonArray2.length(); j++)
&&&&System.out.println(jsonArray2.get(j));
&&} catch (JSONException e) {
&&&// TODO Auto-generated catch block
&&&e.printStackTrace();
Json的制作与使用分别是两个项目,由于刚接触Android,代码比较简单,重在理解原理。
版权所有 爱编程 (C) Copyright 2012. . All Rights Reserved.
闽ICP备号-3
微信扫一扫关注爱编程,每天为您推送一篇经典技术文章。

参考资料

 

随机推荐