androidjson的使用
⑴ android 怎麼用json解析介面(本人新手,請大手幫忙解決下)
fastjson.jar這個jar包可以方便的幫你解析json格式數據:
你可以參考下我這段代碼:
public Object parseMap_Sub(String str) {
try {
Map<String, Object> map = JSON.parseObject(str);
JSONArray jsonArray = (JSONArray) map.get("data");
List<NearMap_Info> list_detial = new ArrayList<NearMap_Info>();
for (Object o : jsonArray) {
Map<String, String> map_1 = (Map<String, String>) o;
NearMap_Info audio_info = new NearMap_Info();
//audio_info.setSize((String) map.get("size"));
audio_info.setFlag(map_1.get("flag"));
audio_info.setTitle(map_1.get("title"));
audio_info.setUrl(map_1.get("url"));
audio_info.setType(map_1.get("type"));
audio_info.setId(map_1.get("id"));
audio_info.setImg(map_1.get("img"));
list_detial.add(audio_info);
}
ro.result = true;
ro.obj = list_detial;
} catch (Exception e) {
e.printStackTrace();
ro.result = false;
}
return ro;
}
⑵ android 在伺服器端生成json格式數據,在客戶端怎麼解析
1、生成JSON格式數據,有對應的後台類處理,如果你是做Android開發,後台提供獲取數據的介面
2、客戶端解決:
java">JSONArrayjsonArr=newJSONArray(json);
for(inti=0;i<jsonArr.length();i++){
JSONObjectjsonObj=jsonArr.getJSONObject(i);
booleanisChild=jsonObj.has("childrenNodes");
AreaBeanbean=newAreaBean(jsonObj.getString("id"),
jsonObj.getString("parentId"),
jsonObj.getString("name"));
mList.add(bean);
if(isChild){
mchildNodesList.add(jsonObj.getString("childrenNodes"));
}else{
mchildNodesList.add(null);
}
}
⑶ android 怎樣將數據以json格式保存在手機文件中
json是一種輕量級數據交換格式,可以包含對象和數組,以下是一個json字元串的示例:
{"key":[{"key1":"value1","key2":value2",...}]}
json只是一種數據交換格式,並不是存儲格式,所以只要你正確地組織好json字元串後,跟其他文件是一樣存儲的;
同時建議你,如果你存儲的數據量比較多的話,建議存儲在android系統自帶的sqlite資料庫中,這樣操作起數據來更方便簡單;如果數據量非常少,只有三五個欄位存儲,那樣使用android的SharedPreferences可能會是更好的選擇,希望你根據應用需求適當選用。
⑷ 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文件
比如說讀取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了。
⑹ android使用JSON遇到的坑(1)
最近在開發的過程中遇到一個問題,服務端返回了一個JSON對象,在用JSON庫解析的時候出現了一個詭異的問題
服務端返回的原始JSON是
在程序中直接調用JSON中的方法
列印的日誌如下
通過JSON的方法取到的結果出現了不一致的情況。應該是轉換的時候精度出現了損失,一步一步跟到內部的實現方法,先看optLong()
這里調用了兩個參數的optLong()方法,在不傳默認值的時候如果出錯的話這個方法會返回0。再往裡跟,這個方法內部調用了JSON.toLong()方法。
接著向裡面走
看來問題是出在這里了,當輸入的參數為String的時候,toLong()方法會使用Double.parseDouble()方法解析,而我們知道double的精度是會有損失的,在 Google的文檔 上有這么一句話
在取非常大的數字的時候,會先轉換成String,再通過parseDouble()方法轉成long,這期間就造成了精度損失。
先得到String類型的值,再將String轉成long
這樣就可以正確的取到值了,Long.valueOf()內部實現調用了BigInteger中的方法,這樣就能保證結果正確了。
⑺ Android 解析json問題
///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();
}
⑻ 如何使用JSON連接Android和php Mysql資料庫
使用JSON連接Android和PHP Mysql資料庫方法:
1、打開安裝WAMP Server的文件夾,打開www文件夾,為你的項目創建一個新的文件夾。必須把項目中所有的文件放到這個文件夾中。
2、新建一個名為android_connect的文件夾,並新建一個php文件,命名為test.php,嘗試輸入一些簡單的php代碼(如下所示)。
test.php
<?php
echo"Welcome, I am connecting Android to PHP, MySQL";
?>
3、創建MySQL資料庫和表
創建了一個簡單的只有一張表的資料庫。用這個表來執行一些示例操作。現在,請在瀏覽器中輸入http://localhost/phpmyadmin/,並打開phpmyadmin。你可以用PhpMyAdmin工具創建資料庫和表。
創建資料庫和表:資料庫名:androidhive,表:proct
CREATE TABLE procts(
pid int(11) primary key auto_increment,
name varchar(100) not null,
price decimal(10,2) not null,
description text,
created_at timestamp default now(),
updated_at timestamp
);
4、用PHP連接MySQL資料庫
現在,真正的伺服器端編程開始了。新建一個PHP類來連接MYSQL資料庫。這個類的主要功能是打開資料庫連接和在不需要時關閉資料庫連接。
新建兩個文件db_config.php,db_connect.php
db_config.php--------存儲資料庫連接變數
db_connect.php-------連接資料庫的類文件
db_config.php
<?php
/*
* All database connection variables
*/
define('DB_USER', "root"); // db user
define('DB_PASSWORD', ""); // db password (mention your db password here)
define('DB_DATABASE', "androidhive"); // database name
define('DB_SERVER', "localhost"); // db server
?>
5、在PHP項目中新建一個php文件,命名為create_proct.php,並輸入以下代碼。該文件主要實現在procts表中插入一個新的產品。
<?php
/*
* Following code will create a new proct row
* All proct details are read from HTTP Post Request
*/
⑼ android 用JSON 解析數據介面方法
介面獲取下來的數據為
{"status":200,"message":"查詢成功","data":{"id":32,"user_id":null,"user_code":null,"user_pass":null,"meeting_id":"1","meeting_pass":null,"config_param_ip":"11.1.1.70","port":"6501","web_config_param_ip":"11.1.1.70","web_port":"6501","unit_code":null,"create_time":null,"update_time":null,"status":0,"userCode":"video1","userPass":"video1","meetingId":"1","meetingPass":"","apiPort":"13000","username":"admin","password":"123456","updateTime":"2021-11-08 17:45:29"}}
使用方法
try {
JSONObject jsonObject = new JSONObject(outstring);
int resultCode = jsonObject.getInt("status");
if (resultCode == 200) {
JSONObject obj = jsonObject.getJSONObject("data");
IP = obj.getString("config_param_ip");
port = obj.getString("web_port");
username = obj.getString("userCode");
password = obj.getString("userPass");
roomID = Integer.parseInt(obj.getString("meetingId"));
roomPassword = obj.getString("password");
} else {
ToastUtils.showShort("查詢失敗");
}
goVideo();
} catch (Exception e) {
e.printStackTrace();
}
⑽ 利用Github保存json文件在Android端接收使用
1.自己注冊好GitHub,創建倉庫等等。
2.新建一個文本文件,輸入要保存的數據,比如
然後保存,然後修改後綴名,其它後綴名應該也可以,我這里修改為.js文件
3.用Git該文件提交到GitHub,比如我的提交到HdyLove/Json/article.js,然後輸入地址類似 https://qiusunshine.github.io/HdyLove/Json/article.js 即可訪問相應的地址,具體用戶名,倉庫名修改為自己的就可以了。
我是使用Volley+Glide使用的,Volley的JsonObjectRequest可以將該網址內容解析為json格式,用AndroidStudio自帶的Json處理方法即可處理