androidlist轉json
1. 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());
2. android如何將list轉化為json
可以通過jsonObject作為中間轉換橋梁,先把你的list轉換為jsonObject,然後jsonObject toString(),即可轉換為json字元串。但是過於復雜的map對象貌似不行,這樣你就只有自己寫了
3. 解析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;
}
4. android怎麼把json轉換為hashmap
在android中把json轉換為hashmap,代碼如下:
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import com.wideyou.model.ExpressOrder;
import com.wideyou.warehouse.model.Storage;
public class HelperFunction {
public ExpressOrder ExpressOrderClassCast(JSONObject reserJson){
ExpressOrder expressOrder=new ExpressOrder();
expressOrder.setCid(Integer.parseInt(reserJson.getString("userId")));
expressOrder.setSendPerson(reserJson.getString("sendPerson"));
expressOrder.setSendPhone(reserJson.getString("sendPhone"));
expressOrder.setSendAddress(reserJson.getString("sendAddress"));
expressOrder.setBeginAddress(reserJson.getString("beginAddress"));
expressOrder.setOtherDes(reserJson.getString("otherDes"));
expressOrder.setEndAddress(reserJson.getString("endAddress"));
expressOrder.setReservPerson(reserJson.getString("reservPerson"));
expressOrder.setReservPhone(reserJson.getString("reservPhone"));
expressOrder.setReservAddress(reserJson.getString("reservAddress"));
expressOrder.setPostCode(reserJson.getString("reservAddress"));
expressOrder.setPayId(Integer.parseInt(reserJson.getString("payId")));
return expressOrder;
}
public Storage StorageClassCast(JSONObject reserJson){
Storage storage=new Storage();
storage.setSname(reserJson.getString("sname"));
storage.setCount(Integer.parseInt(reserJson.getString("count")));
return storage;
}
public static int getCid(JSONObject reserJson, boolean isConsumer){
if(isConsumer){
return Integer.parseInt(reserJson.getString("userId"));
}else{
return Integer.parseInt(reserJson.getString("memberId"));
}
}
//map轉換為json字元串
public static String hashMapToJson(HashMap map) {
String string = "{";
for (Iterator it = map.entrySet().iterator(); it.hasNext();) {
Entry e = (Entry) it.next();
string += "'" + e.getKey() + "':";
string += "'" + e.getValue() + "',";
}
string = string.substring(0, string.lastIndexOf(","));
string += "}";
return string;
}
public static void JsonObject2HashMap(JSONObject jo, List> rstList) {
for (Iterator keys = jo.keys(); keys.hasNext();) {
try {
String key1 = keys.next();
System.out.println("key1---" + key1 + "------" + jo.get(key1)
+ (jo.get(key1) instanceof JSONObject) + jo.get(key1)
+ (jo.get(key1) instanceof JSONArray));
if (jo.get(key1) instanceof JSONObject) {
JsonObject2HashMap((JSONObject) jo.get(key1), rstList);
continue;
}
if (jo.get(key1) instanceof JSONArray) {
JsonArray2HashMap((JSONArray) jo.get(key1), rstList);
continue;
}
System.out.println("key1:" + key1 + "----------jo.get(key1):"
+ jo.get(key1));
json2HashMap(key1, jo.get(key1), rstList);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public static void JsonArray2HashMap(JSONArray joArr,
List> rstList) {
for (int i = 0; i < joArr.size(); i++) {
try {
if (joArr.get(i) instanceof JSONObject) {
JsonObject2HashMap((JSONObject) joArr.get(i), rstList);
continue;
}
if (joArr.get(i) instanceof JSONArray) {
JsonArray2HashMap((JSONArray) joArr.get(i), rstList);
continue;
}
System.out.println("Excepton~~~~~");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public static void json2HashMap(String key, Object value,
List> rstList) {
HashMap map = new HashMap();
map.put(key, value);
rstList.add(map);
}
}
5. android 怎樣將數據以json格式保存在手機文件中
json是一種輕量級數據交換格式,可以包含對象和數組,以下是一個json字元串的示例:
{"key":[{"key1":"value1","key2":value2",...}]}
json只是一種數據交換格式,並不是存儲格式,所以只要你正確地組織好json字元串後,跟其他文件是一樣存儲的;
同時建議你,如果你存儲的數據量比較多的話,建議存儲在android系統自帶的SQLite資料庫中,這樣操作起數據來更方便簡單;如果數據量非常少,只有三五個欄位存儲,那樣使用android的SharedPreferences可能會是更好的選擇,希望你根據應用需求適當選用。
6. android 怎麼看json數據格式
給服務端發送請求後,服務端會返回一連串的數據,這些數據在大部分情況下都是XML格式或者JSON格式。然後JSON相對XML來說解析相對方便一些,所以先說說JSON的解析。
JSON的基本數據格式有這幾種:
1.一個JSON對象——JSONObject
{"name":"胡小威" , "age":20 , "male":true}
2.一個JSON數組——JSONArray
[{"name":"胡小威" , "age":20 , "male":true},{"name":"趙小亮" , "age":22 , "male":false}]
3.復雜一點的JSONObject
{"name":"胡小威", "age"=20, "male":true, "address":{"street":"嶽麓山南", "city":"長沙","country":"中國"}}
4.復雜一點的JSONArray
[
{"name":"胡小威", "age"=20, "male":true, "address":{"street":"嶽麓山南", "city":"長沙","country":"中國"}},
{"name":"趙小亮", "age"=22, "male":false, "address":{"street":"九州港", "city":"珠海","country":"中國"}}
]
5.來個更復雜的,這是我從愛幫公交上扒取的數據
{"buses":{"bus":[{"last_foot_dist":"0","time":"37","segments":{"segment":[{"line_name":"立珊專線(中南大學學生公寓-長沙火車站)","foot_dist":"362","stat_xys":"","stats":"嶽麓山南;湖南師大;二里半;嶽麓山北;市四醫院;華圖教育(太平街口);牛耳教育(南陽街口);韭菜園;曙光路口;長島路口;長沙火車站","end_stat":"長沙火車站","line_xys":"","line_dist":"7535","start_stat":"嶽麓山南"}]},"foot_dist":"362","dist":"7897"},{"last_foot_dist":"0","time":"41","segments":{"segment":[{"line_name":"旅1路(科教新村-長沙火車站)","foot_dist":"337","stat_xys":"","stats":"嶽麓山南;湖南師大;二里半;嶽麓山北;市四醫院;華圖教育(太平街口);蔡鍔中路口;韭菜園;喬庄;曙光路口;長島路口;五一東村;車站路口;長沙火車站","end_stat":"長沙火車站","line_xys":"","line_dist":"7822","start_stat":"嶽麓山南"}]},"foot_dist":"337","dist":"8159"}]}}
接下來是解析部分
一、直接解析
1.{"name":"胡小威" , "age":20 , "male":true}
Java代碼
public void parseJsonObject(String json) {
try {
JSONObject jsonObject = new JSONObject(json);
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
boolean male = jsonObject.getBoolean("male");
//接下來該幹嘛幹嘛
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
2.[{"name":"胡小威" , "age":20 , "male":true},{"name":"趙小亮" , "age":22 , "male":false}]
Java代碼
public void parseJSONArray(String json) {
try {
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
boolean male = jsonObject.getBoolean("male");
//接下來該幹嘛幹嘛
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
3.{"name":"胡小威", "age"=20, "male":true, "address":{"street":"嶽麓山南", "city":"長沙","country":"中國"}}
Java代碼
public void parseJsonPerson(String json) {
try {
JSONObject jsonObject = new JSONObject(json);
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
boolean male = jsonObject.getBoolean("male");
JSONObject addressJSON = jsonObject.getJSONObject("address");
String street = addressJSON.getString("street");
String city = addressJSON.getString("city");
String country = addressJSON.getString("country");
Address address = new Address(street, city, country);
Person person = new Person(name, age, male, address);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
4.
[
{"name":"胡小威", "age"=20, "male":true, "address":{"street":"嶽麓山南", "city":"長沙","country":"中國"}},
{"name":"趙小亮", "age"=22, "male":false, "address":{"street":"九州港", "city":"珠海","country":"中國"}}
]
Java代碼
public void parseJsonArrayPerson(String json) {
List<Person> persons = new ArrayList<Person>();
try {
jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
boolean male = jsonObject.getBoolean("male");
JSONObject addressJSON = jsonObject.getJSONObject("address");
String street = addressJSON.getString("street");
String city = addressJSON.getString("city");
String country = addressJSON.getString("country");
Address address = new Address(street, city, country);
Person person = new Person(name, age, male, address);
persons.add(person);
Log.v("juno", person.toString());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.v("juno", persons.toString());
}
5. {"buses":{"bus":[{"last_foot_dist":"0","time":"37","segments":{"segment":[{"line_name":"立珊專線(中南大學學生公寓-長沙火車站)","foot_dist":"362","stat_xys":"","stats":"嶽麓山南;湖南師大;二里半;嶽麓山北;市四醫院;華圖教育(太平街口);牛耳教育(南陽街口);韭菜園;曙光路口;長島路口;長沙火車站","end_stat":"長沙火車站","line_xys":"","line_dist":"7535","start_stat":"嶽麓山南"}]},"foot_dist":"362","dist":"7897"},{"last_foot_dist":"0","time":"41","segments":{"segment":[{"line_name":"旅1路(科教新村-長沙火車站)","foot_dist":"337","stat_xys":"","stats":"嶽麓山南;湖南師大;二里半;嶽麓山北;市四醫院;華圖教育(太平街口);蔡鍔中路口;韭菜園;喬庄;曙光路口;長島路口;五一東村;車站路口;長沙火車站","end_stat":"長沙火車站","line_xys":"","line_dist":"7822","start_stat":"嶽麓山南"}]},"foot_dist":"337","dist":"8159"}]}}
Java代碼
public List<Salution> parseJSON(String str){
Log.d("返回的JSON數據:", str);
List<Salution> busList = new ArrayList<Salution>();
try {
JSONObject jsonObject = new JSONObject(str);
JSONObject busesJSON = jsonObject.getJSONObject("buses");
JSONArray busJSArray=busesJSON.getJSONArray("bus");
for(int i=0;i<busJSArray.length();i++){
JSONObject busJSObject = busJSArray.getJSONObject(i);
JSONObject segsJSObject=busJSObject.getJSONObject("segments");
JSONArray segJSArray=segsJSObject.getJSONArray("segment");
Salution st=new Salution();
for(int j=0;j<segJSArray.length();j++){
if(j==0){
JSONObject segJSObject = segJSArray.getJSONObject(j);
st.setLine_name1(segJSObject.getString("line_name"));
Log.d("line_name", segJSObject.getString("line_name"));
st.setStats1(segJSObject.getString("stats"));
st.setEnd_stat1(segJSObject.getString("end_stat"));
st.setStart_stat1(segJSObject.getString("start_stat"));
}
if(j==1){
JSONObject segJSObject = segJSArray.getJSONObject(j);
st.setLine_name2(segJSObject.getString("line_name"));
Log.d("line_name", segJSObject.getString("line_name"));
st.setStats2(segJSObject.getString("stats"));
st.setEnd_stat2(segJSObject.getString("end_stat"));
st.setStart_stat2(segJSObject.getString("start_stat"));
}
}
busList.add(st);
}
return busList;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
這里我只是簡單獲取了幾個我想要的數據。
二、使用JSON類庫Gson 來解析JSON
Gson 是 Google 提供的用來在 Java 對象和 JSON 數據之間進行映射的 Java 類庫。可以將一個 JSON 字元串轉成一個 Java 對象,或者反過來。
首先,從 code.google.com/p/google-gson/downloads/list下載GsonAPI
Java代碼
google-gson-1.7.1-release.zip
再把gson-1.7.jar 到libs
可以使用兩種方法解析
①、通過獲取JsonReader對象解析JSON數據:
Java代碼
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();
}
②、通過把JSON數據映射成一個對象,使用Gson對象的fromJson()方法獲取一個對象數組進行操作
Java代碼
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());
}
我一般是採用直接解析,添加類庫神馬的最討厭了···
還有,抱怨一下,iteye的編輯弱爆了!!!
轉載