當前位置:首頁 » 安卓系統 » android讀取json文件

android讀取json文件

發布時間: 2023-08-17 20:46:50

『壹』 android json解析三種方式哪種效率最高

用org.json以及谷歌提供gson來解析json數據的方式更好一些。

安卓下通常採用以下幾種方式解析json數據:
1、org.json包(已經集成到android.jar中了)
2、google提供的gson庫
3、阿里巴巴的fastjson庫
4、json-lib

以Google出品的Gson為例,具體步驟為:
1、首先,從 code.google.com/p/google-gson/downloads/list下載GsonAPI:
google-gson-1.7.1-release.zip 把gson-1.7.jar 到libs(項目根目錄新建一個libs文件夾)中。 可以使用以下兩種方法解析JSON數據,通過獲取JsonReader對象解析JSON數據。
代碼如下:
String jsonData = "[{\"username\":\"arthinking\",\"userId\":001},{\"username\":\"Jason\",\"userId\":002}]";
try{
JsonReader reader = new JsonReader(new StringReader(jsonData));
reader.beginArray();
while(reader.hasNext()){
reader.beginObject();
while(reader.hasNext()){
String tagName = reader.nextName();
if(tagName.equals("username")){
System.out.println(reader.nextString());
}
else if(tagName.equals("userId")){
System.out.println(reader.nextString());
}
}
reader.endObject();
}
reader.endArray();
}
catch(Exception e){
e.printStackTrace();
}
2、使用Gson對象獲取User對象數據進行相應的操作:
代碼如下:

Type listType = new TypeToken<LinkedList<User>>(){}.getType();
Gson gson = new Gson();
LinkedList<User> users = gson.fromJson(jsonData, listType);
for (Iterator iterator = users.iterator(); iterator.hasNext();) {
User user = (User) iterator.next();
System.out.println(user.getUsername());
System.out.println(user.getUserId());
}
3、如果要處理的JSON字元串只包含一個JSON對象,則可以直接使用fromJson獲取一個User對象:
代碼如下:

String jsonData = "{\"username\":\"arthinking\",\"userId\":001}";
Gson gson = new Gson();
User user = gson.fromJson(jsonData, User.class);
System.out.println(user.getUsername());
System.out.println(user.getUserId());

『貳』 Android 解析json問題

java">///http地址
StringhttpUrl=ip+":"+埠號+"/loginbyandroid/validate.do";
//HttpPost連接對象
HttpPosthttpRequest=newHttpPost(httpUrl);
//使用NameValuePair來保存要傳遞的Post參數
List<NameValuePair>params=newArrayList<NameValuePair>();
//添加要傳遞的參數
params.add(newBasicNameValuePair("loginId","value"));
params.add(newBasicNameValuePair("password","value"));
//設置字元集
HttpEntityhttpentity;
try{
httpentity=newUrlEncodedFormEntity(params,"utf-8");

//請求httpRequest
httpRequest.setEntity(httpentity);
//取得默認的HttpClient
HttpClienthttpclient=newDefaultHttpClient();
//取得HttpResponse
HttpResponsehttpResponse;
httpResponse=httpclient.execute(httpRequest);
//HttpStatus.SC_OK表示連接成功
if(httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
//取得返回的字元串
StringstrResult=EntityUtils.toString(httpResponse
.getEntity());
JSONArrayjsonArray=newJSONArray(strResult);
for(inti=0;i<jsonArray.length();i++){
JSONObjectjsonObject=(JSONObject)jsonArray.opt(i);
Stringsuccess=jsonObject.getString("success");
StringJSESSIONID=jsonObject.getString("JSESSIONID");
StringloginName=jsonObject.getString("loginName");
Stringorgname=jsonObject.getString("orgname");
System.out.println("success="+success
+"JSESSIONID="+JSESSIONID+"loginName="
+loginName+"orgname="+orgname);
}
}else{
System.out.println("請求錯誤!");
}
}catch(ClientProtocolExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}

『叄』 Android 中解析 JSON

JSON( JavaScript Object Notation ) 是一種輕量級的數據交換格式。易於閱讀和編寫,同時也易於機器解析和生成。

JSON 建構於兩種結構:

JSON 具有以下這些格式:

參考: Android 中 解析 JSON

Android 提供類四種不同的類來操作 JSON 數據。這些類是 JSONArray、JSONObject、JSONStringer 和 JSONTokenizer

為了解析 JSON 對象,須先創建一個 JSONObject 類的對象,需要傳入需解析的字元串 JSONObject root = new JSONObject(candyJson); 然後根據 JSONObject 對象提供方法以及數據類型解析對應 json 數據。下表展示一些 JSONObiect 提供的方法

示例:

『肆』 android怎麼遍歷jsonobject

android 讀取json數據(遍歷JSONObject和JSONArray)
•public String getJson(){

• String jsonString = "{\"FLAG\":\"flag\",\"MESSAGE\":\"SUCCESS\",\"name\":[{\"name\":\"jack\"},{\"name\":\"lucy\"}]}";//json字元串
• try {
• JSONObject result = new JSONObject(jsonstring);//轉換為JSONObject
• int num = result.length();
• JSONArray nameList = result.getJSONArray("name");//獲取JSONArray
• int length = nameList.length();
• String aa = "";
• for(int i = 0; i < length; i++){//遍歷JSONArray
• Log.d("debugTest",Integer.toString(i));
• JSONObject oj = nameList.getJSONObject(i);
• aa = aa + oj.getString("name")+"|";

• }
• Iterator<?> it = result.keys();
• String aa2 = "";
• String bb2 = null;
• while(it.hasNext()){//遍歷JSONObject
• bb2 = (String) it.next().toString();
• aa2 = aa2 + result.getString(bb2);

• }
• return aa;
• } catch (JSONException e) {
• throw new RuntimeException(e);
• }
• }

『伍』 android 讀取網上JSON,數據重復,該怎麼處理

重復就重復唄,對你程序又沒任何影響,你實在不想重復你就這樣寫

class A()
{
String date;
String formatDate;
List<B> bList;

//實現他們的get,set方法
}

class B()
{
String time;
String title;
String type;
String url;
String keywords;
//實現他們的get,set方法
}

代碼里這樣寫

A a = new A();
List<A> aList=new List<A>();
for (int i = 0; i < array.length; i++) {
JSONObject item=array.getJSonObject(i);
String Date=item.getString("date");
String formatDate=item.getString("formatDate");
a.setDate(Date);
a.setformatDate(formatDate);
JsonArray next=item.getJSONArray("list");
List<B> list = new ArrayList<B>();
for (int j = 0; j < next.length; j++) {
B b=new B();
b.setTime();
b.setType();
...
list.add(b);

}
a.setBList(list);
aList.add(a);
}

『陸』 android載入assets中的json格式文件

assets資源目錄一般用於存放html文件、資料庫文件、javascript文件,assets目錄下的文件不會在R.java自動生成ID,所以讀取assets目錄下的文件必須指定文件的路徑

在代碼中使用AssertManager獲取文件的輸入流讀取

AssetManagerassetManager=context.getAssets();
try{
InputStreamis=assetManager.open("json.data");
BufferedReaderbr=newBufferedReader(newInputStreamReader(is));
StringBufferstringBuffer=newStringBuffer();
Stringstr=null;
while((str=br.readLine())!=null){
stringBuffer.append(str);
}

}catch(IOExceptione){
e.printStackTrace();
}


也可以把json文件放在res的raw目錄下

res/raw中的文件會被映射到R.java文件中,訪問的時候直接使用資源ID即R.id.filename;

但是需要注意的是assets允許有目錄結構,而raw不行

讀取方法大同小異

try{
InputStreamis=getResources().openRawResource(R.id.file);
BufferedReaderbr=newBufferedReader(newInputStreamReader(is));
StringBufferstringBuffer=newStringBuffer();
Stringstr=null;
while((str=br.readLine())!=null){
stringBuffer.append(str);
}

}catch(IOExceptione){
e.printStackTrace();
}

『柒』 android怎麼讀取外部json文件

比如說讀取sd卡里的
privatestaticStringSDCardPATH=Environment.getExternalStorageDirectory()+"/";

/**
*讀取文本文件
*
*@paramfilePath
*@return
*/
(StringfilePath){
StringBuildersb=newStringBuilder();
try{
Filefile=newFile(SDCardPATH+filePath);
InputStreamin=null;
in=newFileInputStream(file);
inttempbyte;
while((tempbyte=in.read())!=-1){
sb.append((char)tempbyte);
}
in.close();
}catch(Exceptione){
e.printStackTrace();
}
returnsb.toString();
}


然後你就可以進行你的解析json了。

熱點內容
源碼下載靠譜 發布:2025-09-13 14:27:30 瀏覽:954
倉庫解壓碼流 發布:2025-09-13 14:20:30 瀏覽:884
在線編程少兒 發布:2025-09-13 14:19:29 瀏覽:382
365文檔的停止保護密碼是多少 發布:2025-09-13 14:04:18 瀏覽:137
c語言二級編程題 發布:2025-09-13 13:59:09 瀏覽:832
linux網卡dhcp 發布:2025-09-13 13:58:58 瀏覽:679
伺服器繁忙請重試怎麼辦 發布:2025-09-13 13:51:05 瀏覽:42
手機視頻怎樣壓縮最小 發布:2025-09-13 13:20:13 瀏覽:249
java編程思想第五版 發布:2025-09-13 13:06:08 瀏覽:406
手機禁止程序訪問網路連接網路連接 發布:2025-09-13 13:06:07 瀏覽:342