Android-Gson(シロが記録)
3954 ワード
//
String jsonarray = "[{\"id\":\"001\",\"name\":\"zhang1\",\"age\":\"12\"},"
+ "{\"id\":\"002\",\"name\":\"zhang2\",\"age\":\"13\"},"
+ "{\"id\":\"003\",\"name\":\"zhang3\",\"age\":\"13\"},"
+ "{\"id\":\"004\",\"name\":\"zhang4\",\"age\":\"14\"}]";
String jsonobj = "{\"id\":\"004\",\"name\":\"zhang4\",\"age\":\"15\"}";
// JsonUtils
List<User> users = JsonUtils.parseJson(jsonarray);
StringBuffer sb = new StringBuffer();
for (User user : users) {
String str = user.toString();
sb.append(str);
sb.append("
");
}
textView.setText(sb.toString());
// JsonUtils
List<User> users = JsonUtils.parseJosnArray(jsonarray);
StringBuffer sb = new StringBuffer();
for (User user : users) {
String str = user.toString();
sb.append(str);
sb.append("
");
}
textView.setText(sb.toString())
// JsonUtils
List<User> users = JsonUtils.parseJsonObject(jsonobj);
StringBuffer sb = new StringBuffer();
for (User user : users) {
String str = user.toString();
sb.append(str);
sb.append("
");
}
textView.setText(sb.toString());
//
import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
public class JsonUtils {
public static List<User> parseJosnArray(String jsonData) {
List<User> users = null;
User user = null;
@SuppressWarnings("resource")
JsonReader reader = new JsonReader(new StringReader(jsonData));
try {
reader.beginArray();
while (reader.hasNext()) {
users = new ArrayList<User>();
reader.beginObject();
while (reader.hasNext()) {
user = new User();
String type = reader.nextName();
if (type.equals("id")) {
user.setId(reader.nextString());
} else if (type.equals("name")) {
user.setName(reader.nextString());
} else if (type.equals("age")) {
user.setAge(reader.nextString());
}
users.add(user);
}
reader.endObject();
}
reader.endArray();
} catch (IOException e) {
e.printStackTrace();
}
return users;
}
public static List<User> parseJsonObject(String jsonData){
List<User> users = new ArrayList<User>();
Gson gson=new Gson();
User user=gson.fromJson(jsonData, User.class);
users.add(user);
return users;
}
public static List<User> parseJson(String jsonData){
User user=null;
List<User> users=new ArrayList<User>();
Type listType=new TypeToken<LinkedList<User>>(){}.getType();
Gson gson=new Gson();
LinkedList<User> linkedList=gson.fromJson(jsonData, listType);
for (@SuppressWarnings("rawtypes")
Iterator iterator = linkedList.iterator(); iterator.hasNext();) {
user = (User) iterator.next();
users.add(user);
}
return users;
}
}
// , ,
google-gson-2.2.4-release