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的编辑弱爆了!!!
转载