android寫入json
1. Android開發中為什麼很少使用JSON存儲數據
是可以用JSON存儲數據對象的,而且也是Google推薦的,可以取代以實現Serializable來存儲對象的方法。下面是使用JSON存儲數據的原因。
Android開發中,涉及到對象存儲,通常的做法是直接實現`Serializable`。有關這個介面,它保證了實現該介面的類的對象能夠被`ObjectOutput/InputStream`直接輸入輸出,即序列化。這很方便,但是也很不好。
提到『序列化』,大多數人都想到`Serializable`,而實際上『序列化』的只是指「將對象的狀態信息轉換為可以存儲或傳輸的形式的過程」,java的`Serializabe`是位元組序列化的一種。
`Serialziable`的缺點之一是,實現了該介面的類將失去靈活性。這一點《Effective Java》第74條也指出了,實現了這個`Serializable`的類將會依賴這個類的內部演化,根源在於UID(Serial version UID)。如果你沒有指定UID,那麼每次這個類被序列化時都會根據這個類的當前狀態生成一個UID。想像這么一種場景:這個類已經被導出了,比如發給其他公司或部門使用了,然後你又修改了這個類,那麼當你再將這個類發布時,由於UID不同,其他公司或部門的程序員將可能得到一個「InvalidClassException」。
這種情況的根本原因是因為你不能控制序列化的實現,你控制不了UID的生成過程。這就需要一個自定義的序列化形式。在Android中,Google推薦JSON序列化。而且Android程序員也可以使用Gson等工具來進行序列化和反序列化。
和`Serializable`的位元組序列化不同,JSON序列化是字元序列化。
此外,`Serializable`只適合存儲對象。由於在傳輸時`Serializalbe`要做大量IO,Android提供了`Parcelable`。
最後,題主不應該把資料庫和JSON,XML比較,如果要比,也只能把資料庫和文件存儲比。資料庫適合存儲數量大,關系復雜的數據,這樣管理,查閱就很方便。與此相對文件存儲適合數量小,關系簡單的數據。
2. android怎麼用gson做本地存儲
Android存儲文件通常可以用SharedPreferences、SQLite、Content Provider和File,但是SharedPreferences只支持簡單的key-value,
通常,如果要存儲一個對象,可以先把它序列化,然後用輸入輸出流存進file文件
另一個我比較喜歡的方式是:
寫:先把一個對象用gson解析成json字元串(使用gson的toJson函數),然後當成一個value寫進SharedPreferences裡面
讀:讀取出來的時候就再次用gson把json解析成對象(使用gson的fromJson函數)
參考:
Android中的JSON詳細總結
怎樣使用Gson 解析 (deserialize) json字元串
Gson簡要使用筆記
代碼實現:
3. android用volley怎麼給伺服器發送json
1.下載官網的android SDK(本人用的是eclipse)
2.新建一個android項目:
File->new->andriod Application project
7、下面就是具體的使用post和get請求的代碼:
A:發送get請求如下:
package com.example.xiaoyuantong;
import java.util.HashMap;
import java.util.Iterator;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
/**
* Demo
*/
public class MainActivity extends Activity {
private RequestQueue requestQueue ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
TextView textView = (TextView)findViewById(R.id.textView);
requestQueue = Volley.newRequestQueue(this);
getJson();
textView.setText("hello");
}
private void getJson(){
String url = "http://192.168.20.1:8080/xiaoyuantong/userAction!register.action?pwd='測試'";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
//這里可以列印出接受到返回的json
Log.e("bbb", response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError arg0) {
// System.out.println("sorry,Error");
Log.e("aaa", arg0.toString());
}
});
requestQueue.add(jsonObjectRequest);
}
}
B:發送post請求如下:
package com.example.xiaoyuantong;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
public class PostActivity extends Activity {
private RequestQueue requestQueue ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
init();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.post, menu);
return true;
}
private void init() {
TextView textView = (TextView)findViewById(R.id.postView);
requestQueue = Volley.newRequestQueue(this);
getJson();
textView.setText("hellopost");
}
private void getJson(){
String url = "http://192.168.20.1:8080/xiaoyuantong/userAction!reg.action";
JsonObjectRequest jsonObjectRequest ;
JSONObject jsonObject=new JSONObject() ;
try {
jsonObject.put("name", "張三");
jsonObject.put("sex", "女");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//列印前台向後台要提交的post數據
Log.e("post",jsonObject.toString());
//發送post請求
try{
jsonObjectRequest = new JsonObjectRequest(
Request.Method.POST, url, jsonObject,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
//列印請求後獲取的json數據
Log.e("bbb", response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError arg0) {
// System.out.println("sorry,Error");
Log.e("aaa", arg0.toString());
}
});
requestQueue.add(jsonObjectRequest);
} catch (Exception e) {
e.printStackTrace();
System.out.println(e + "");
}
requestQueue.start();
}
}
8、在android的logcat裡面能查看到列印的請求
(紅色的顯示的是我在後台請求到數據)
有時候logcat顯示不出數據,可能是消息被過濾了,可以在左邊點擊「減號」刪除過濾
在server端,也就是在myeclipse的建立的另一個後台工程裡面能獲取到請求:
9、後續會補充json數據的解析部分,以及過度到移動雲的部分,上面只是c/s模式下的一個簡單的基於http的請求應答例子。