當前位置:首頁 » 安卓系統 » android對象轉json

android對象轉json

發布時間: 2024-07-27 09:50:15

『壹』 解析json的數據

一則冊、 JSON (javaScript Object Notation)一種簡單的數據格式,比xml更輕巧。
Json建構於兩種結構:
1、「名稱/值」對的集合(A collection of name/value pairs)。不同的語言中,它被理解為對孫廳宏象(object),紀錄(record),結構(struct),字典(dictionary),哈希表(hash table),有鍵列表(keyed list),或者關聯數組 (associative array)。 如:
{
「name」:」jackson」,
「age」:100
}

2、值的有序列表(An ordered list of values)。在大部分語言中,它被理解為數組(array)如:
{
「students」:
[
{「伏枝name」:」jackson」,「age」:100},
{「name」:」michael」,」age」:51}
]
}
二、java解析JSON步驟
A、伺服器端將數據轉換成json字元串
首先、伺服器端項目要導入json的jar包和json所依賴的jar包至builtPath路徑下(這些可以到JSON-lib官網下載:)

然後將數據轉為json字元串,核心函數是:
public static String createJsonString(String key, Object value)
{
JSONObject jsonObject = new JSONObject();
jsonObject.put(key, value);
return jsonObject.toString();
}
B、客戶端將json字元串轉換為相應的javaBean
1、客戶端獲取json字元串(因為android項目中已經集成了json的jar包所以這里無需導入)
public class HttpUtil
{

public static String getJsonContent(String urlStr)
{
try
{// 獲取HttpURLConnection連接對象
URL url = new URL(urlStr);
HttpURLConnection httpConn = (HttpURLConnection) url
.openConnection();
// 設置連接屬性
httpConn.setConnectTimeout(3000);
httpConn.setDoInput(true);
httpConn.setRequestMethod("GET");
// 獲取相應碼
int respCode = httpConn.getResponseCode();
if (respCode == 200)
{
return ConvertStream2Json(httpConn.getInputStream());
}
}
catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}

private static String ConvertStream2Json(InputStream inputStream)
{
String jsonStr = "";
// ByteArrayOutputStream相當於內存輸出流
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
// 將輸入流轉移到內存輸出流中
try
{
while ((len = inputStream.read(buffer, 0, buffer.length)) != -1)
{
out.write(buffer, 0, len);
}
// 將內存流轉換為字元串
jsonStr = new String(out.toByteArray());
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonStr;
}
}
2、獲取javaBean
public static Person getPerson(String jsonStr)
{
Person person = new Person();
try
{// 將json字元串轉換為json對象
JSONObject jsonObj = new JSONObject(jsonStr);
// 得到指定json key對象的value對象
JSONObject personObj = jsonObj.getJSONObject("person");
// 獲取之對象的所有屬性
person.setId(personObj.getInt("id"));
person.setName(personObj.getString("name"));
person.setAddress(personObj.getString("address"));
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}

return person;
}

public static List<Person> getPersons(String jsonStr)
{
List<Person> list = new ArrayList<Person>();

JSONObject jsonObj;
try
{// 將json字元串轉換為json對象
jsonObj = new JSONObject(jsonStr);
// 得到指定json key對象的value對象
JSONArray personList = jsonObj.getJSONArray("persons");
// 遍歷jsonArray
for (int i = 0; i < personList.length(); i++)
{
// 獲取每一個json對象
JSONObject jsonItem = personList.getJSONObject(i);
// 獲取每一個json對象的值
Person person = new Person();
person.setId(jsonItem.getInt("id"));
person.setName(jsonItem.getString("name"));
person.setAddress(jsonItem.getString("address"));
list.add(person);
}
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}

return list;
}

『貳』 android如何將list轉化為json

可以通過jsonObject作為中間轉換橋梁,先把你的list轉換為jsonObject,然後jsonObject toString(),即可轉換為json字元串。但是過於復雜的map對象貌似不行,這樣你就只有自己寫了

『叄』 android js 交互 能傳json對象嗎

最近幾個項目的測試結果,Android無法主動通過調用
webview.loadUrl("javascript:"+callbackFunction+"('"+data+"')"); 這種方式將jsonobject類型的data傳給js,因為js那邊得到就是一個string的對象。

與此同時,js主動調用android的對象方式,android也無法返回給js一個jsonobject,需要js做一下轉換,例如:

Android 代碼:

[java] view plainprint?
WebView mWebView = (WebView) this.findViewById(R.id.webview);
WebSettings settings = mWebView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setPluginsEnabled(true);
settings.setAllowFileAccess(true);

settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);//不加上,會顯示白邊
String url="file:///android_asset/t.html"; //js代碼卸載t.html里
NavigationInstance navigation =new NavigationInstance(this);
mWebView.addJavascriptInterface(navigation, "Navigation");

NavigationInstance里的代碼:

[java] view plainprint?
@Override
public JSONObject GetManeuverInfo() {
try{
JSONObject test=new JSONObject();
test.put("maomao", "value");
return test;
//return new JSONObject(bean.ManeuverInfo);
}catch(Exception e){
Log.e(TAG, "",e);
}
return null;
}

t.html里的代碼:

[javascript] view plainprint?
function testAPI(el){
console.log("---------testAPI---------");
eval("var obj = "+Navigation.GetManeuverInfo());

alert('typeof:'+typeof(obj));
alert('maomao:'+obj.maomao);
alert('obj:'+obj);
}
如果直接寫成 Navigation.GetManeuverInfo.maomao是會提示undefined,因為js那邊只得到了一個string對象而已,它不知道maomao是個key。
通過eval將其轉化成表達式就可以調用obj.maomao得到value。

在此ps一下ios,貌似人家支持webview很好,js可以直接獲取到json對象.

『肆』 android 怎樣將數據以json格式保存在手機文件中

json是一種輕量級數據交換格式,可以包含對象和數組,以下是一個json字元串的示例:
{"key":[{"key1":"value1","key2":value2",...}]}

json只是一種數據交換格式,並不是存儲格式,所以只要你正確地組織好json字元串後,跟其他文件是一樣存儲的;

同時建議你,如果你存儲的數據量比較多的話,建議存儲在android系統自帶的SQLite資料庫中,這樣操作起數據來更方便簡單;如果數據量非常少,只有三五個欄位存儲,那樣使用android的SharedPreferences可能會是更好的選擇,希望你根據應用需求適當選用。

『伍』 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的請求應答例子。

『陸』 android 解析json用那個包裡面的方法比較好呢

android 解析json還有用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());

熱點內容
db2新建資料庫 發布:2024-09-08 08:10:19 瀏覽:170
頻率計源碼 發布:2024-09-08 07:40:26 瀏覽:778
奧迪a6哪個配置帶後排加熱 發布:2024-09-08 07:06:32 瀏覽:100
linux修改apache埠 發布:2024-09-08 07:05:49 瀏覽:208
有多少個不同的密碼子 發布:2024-09-08 07:00:46 瀏覽:566
linux搭建mysql伺服器配置 發布:2024-09-08 06:50:02 瀏覽:995
加上www不能訪問 發布:2024-09-08 06:39:52 瀏覽:811
銀行支付密碼器怎麼用 發布:2024-09-08 06:39:52 瀏覽:513
蘋果手機清理瀏覽器緩存怎麼清理緩存 發布:2024-09-08 06:31:32 瀏覽:554
雲伺服器的優點與缺點 發布:2024-09-08 06:30:34 瀏覽:734