志在指尖
用双手敲打未来

Android JSON 解析示例代码

来自Google官方的有关Android平台的JSON解析示例,假如远程效劳器运用了json而不是xml的数据提供,在Android
平台上曾经内置的org.json包能够很便当的完成手机客户端的解析处置。下面Android123一同剖析下这个例子,协助
Android开发者需求有关HTTP通讯、正则表达式、JSON解析、appWidget开发的一些学问。Android开发
publicclassWordWidgetextendsAppWidgetProvider{//appWidget
@Override
publicvoidonUpdate(Contextcontext,AppWidgetManagerappWidgetManager,
int[]appWidgetIds){
context.startService(newIntent(context,UpdateService.class));//防止ANR,所以Widget中开了个效劳
}
publicstaticclassUpdateServiceextendsService{
@Override
publicvoidonStart(Intentintent,intstartId){
//Buildthewidgetupdatefortoday
RemoteViewsupdateViews=buildUpdate(this);
ComponentNamethisWidget=newComponentName(this,WordWidget.class);
AppWidgetManagermanager=AppWidgetManager.getInstance(this);
manager.updateAppWidget(thisWidget,updateViews);
}
publicRemoteViewsbuildUpdate(Contextcontext){
//Pickoutmonthnamesfromresources
Resourcesres=context.getResources();
String[]monthNames=res.getStringArray(R.array.month_names);
Timetoday=newTime();
today.setToNow();
StringpageName=res.getString(R.string.template_wotd_title,monthNames[today.month],
today.monthDay);
RemoteViewsupdateViews=null;
StringpageContent=””;
try{
SimpleWikiHelper.prepareUserAgent(context);
pageContent=SimpleWikiHelper.getPageContent(pageName,false);
}catch(ApiExceptione){
Log.e(“WordWidget”,”Couldn’tcontactAPI”,e);
}catch(ParseExceptione){
Log.e(“WordWidget”,”Couldn’tparseAPIresponse”,e);
}
//正则表达式处置,有关定义见下面的SimpleWikiHelper类
Patternpattern=Pattern.compile(SimpleWikiHelper.WORD_OF_DAY_REGEX);
Matchermatcher=pattern.matcher(pageContent);
if(matcher.find()){
updateViews=newRemoteViews(context.getPackageName(),R.layout.widget_word);
StringwordTitle=matcher.group(1);
updateViews.setTextViewText(R.id.word_title,wordTitle);
updateViews.setTextViewText(R.id.word_type,matcher.group(2));
updateViews.setTextViewText(R.id.definition,matcher.group(3).trim());
StringdefinePage=res.getString(R.string.template_define_url,Uri.encode(wordTitle));
IntentdefineIntent=newIntent(Intent.ACTION_VIEW,Uri.parse(definePage));//这里是翻开相
应的网页,所以Uri是http的url,action是view即翻开web阅读器
PendingIntentpendingIntent=PendingIntent.getActivity(context,0/*norequestCode*/,
defineIntent,0/*noflags*/);
updateViews.setOnClickPendingIntent(R.id.widget,pendingIntent);//单击Widget翻开
Activity
}else{
updateViews=newRemoteViews(context.getPackageName(),R.layout.widget_message);
CharSequenceerrorMessage=context.getText(R.string.widget_error);
updateViews.setTextViewText(R.id.message,errorMessage);
}
returnupdateViews;
}
@Override
publicIBinderonBind(Intentintent){
//Wedon’tneedtobindtothisservice
returnnull;
}
}
}
有关网络通讯的实体类,以及一些常量定义如下:
publicclassSimpleWikiHelper{
privatestaticfinalStringTAG=”SimpleWikiHelper”;
publicstaticfinalStringWORD_OF_DAY_REGEX=
“(?s)\\{\\{wotd\\|(.+?)\\|(.+?)\\|([^#\\|]+).*?\\}\\}”;
privatestaticfinalStringWIKTIONARY_PAGE=
“http://en.wiktionary.org/w/api.php?action=query&prop=revisions&titles=%s&”+
“rvprop=content&format=json%s”;
privatestaticfinalStringWIKTIONARY_EXPAND_TEMPLATES=
“&rvexpandtemplates=true”;
privatestaticfinalintHTTP_STATUS_OK=200;
privatestaticbyte[]sBuffer=newbyte[512];
privatestaticStringsUserAgent=null;
publicstaticclassApiExceptionextendsException{
publicApiException(StringdetailMessage,Throwablethrowable){
super(detailMessage,throwable);
}publicApiException(StringdetailMessage){
super(detailMessage);
}
}
publicstaticclassParseExceptionextendsException{
publicParseException(StringdetailMessage,Throwablethrowable){
super(detailMessage,throwable);
}
}
publicstaticvoidprepareUserAgent(Contextcontext){
try{
//Readpackagenameandversionnumberfrommanifest
PackageManagermanager=context.getPackageManager();
PackageInfoinfo=manager.getPackageInfo(context.getPackageName(),0);
sUserAgent=String.format(context.getString(R.string.template_user_agent),
info.packageName,info.versionName);
}catch(NameNotFoundExceptione){
Log.e(TAG,”Couldn’tfindpackageinformationinPackageManager”,e);
}
}
publicstaticStringgetPageContent(Stringtitle,booleanexpandTemplates)
throwsApiException,ParseException{
StringencodedTitle=Uri.encode(title);
StringexpandClause=expandTemplates?WIKTIONARY_EXPAND_TEMPLATES:””;
Stringcontent=getUrlContent(String.format(WIKTIONARY_PAGE,encodedTitle,expandClause));
try{
JSONObjectresponse=newJSONObject(content);
JSONObjectquery=response.getJSONObject(“query”);
JSONObjectpages=query.getJSONObject(“pages”);
JSONObjectpage=pages.getJSONObject((String)pages.keys().next());
JSONArrayrevisions=page.getJSONArray(“revisions”);
JSONObjectrevision=revisions.getJSONObject(0);
returnrevision.getString(“*”);
}catch(JSONExceptione){
thrownewParseException(“ProblemparsingAPIresponse”,e);
}
}
protectedstaticsynchronizedStringgetUrlContent(Stringurl)throwsApiException{
if(sUserAgent==null){
thrownewApiException(“User-Agentstringmustbeprepared”);
}
HttpClientclient=newDefaultHttpClient();
HttpGetrequest=newHttpGet(url);
request.setHeader(“User-Agent”,sUserAgent);//设置客户端标识
try{
HttpResponseresponse=client.execute(request);
StatusLinestatus=response.getStatusLine();
if(status.getStatusCode()!=HTTP_STATUS_OK){
thrownewApiException(“Invalidresponsefromserver:”+status.toString());
}
HttpEntityentity=response.getEntity();
InputStreaminputStream=entity.getContent();//获取HTTP返回的数据流
ByteArrayOutputStreamcontent=newByteArrayOutputStream();
intreadBytes=0;
while((readBytes=inputStream.read(sBuffer))!=-1){
content.write(sBuffer,0,readBytes);//转化为字节数组流
}
returnnewString(content.toByteArray());//从字节数组构建String
}catch(IOExceptione){
thrownewApiException(“ProblemcommunicatingwithAPI”,e);
}
}
}
有关整个每日维基的widget例子比拟简单,主要是协助大家积聚常用代码,
理解Android平台JSON的处置方式,毕竟很多Server还是Java的。

未经允许不得转载:IT技术网站 » Android JSON 解析示例代码
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!

 

志在指尖 用双手敲打未来

登录/注册IT技术大全

热门IT技术

C#基础入门   SQL server数据库   系统SEO学习教程   WordPress小技巧   WordPress插件   脚本与源码下载