Ogu*_*han 73 java arrays android json gson
我想解析JSON数组并使用gson.首先,我可以记录JSON输出,服务器明确地响应客户端.
这是我的JSON输出:
[
{
id : '1',
title: 'sample title',
....
},
{
id : '2',
title: 'sample title',
....
},
...
]
Run Code Online (Sandbox Code Playgroud)
我试过这个结构进行解析.一个类,它依赖于单个array和ArrayList所有JSONArray.
public class PostEntity {
private ArrayList<Post> postList = new ArrayList<Post>();
public List<Post> getPostList() {
return postList;
}
public void setPostList(List<Post> postList) {
this.postList = (ArrayList<Post>)postList;
}
}
Run Code Online (Sandbox Code Playgroud)
发布课程:
public class Post {
private String id;
private String title;
/* getters & setters */
}
Run Code Online (Sandbox Code Playgroud)
当我尝试使用gson没有错误,没有警告和没有日志:
GsonBuilder gsonb = new GsonBuilder();
Gson gson = gsonb.create();
PostEntity postEnt;
JSONObject jsonObj = new JSONObject(jsonOutput);
postEnt = gson.fromJson(jsonObj.toString(), PostEntity.class);
Log.d("postLog", postEnt.getPostList().get(0).getId());
Run Code Online (Sandbox Code Playgroud)
怎么了,怎么解决?
yor*_*rkw 223
你可以JSONArray直接解析,不需要再一次包装你的Post类,PostEntity也不需要新的JSONObject().toString():
Gson gson = new Gson();
String jsonOutput = "Your JSON String";
Type listType = new TypeToken<List<Post>>(){}.getType();
List<Post> posts = gson.fromJson(jsonOutput, listType);
Run Code Online (Sandbox Code Playgroud)
希望有所帮助.
我正在寻找一种以更通用的方式解析对象数组的方法; 这是我的贡献:
CollectionDeserializer.java:
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
public class CollectionDeserializer implements JsonDeserializer<Collection<?>> {
@Override
public Collection<?> deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
Type realType = ((ParameterizedType)typeOfT).getActualTypeArguments()[0];
return parseAsArrayList(json, realType);
}
/**
* @param serializedData
* @param type
* @return
*/
@SuppressWarnings("unchecked")
public <T> ArrayList<T> parseAsArrayList(JsonElement json, T type) {
ArrayList<T> newArray = new ArrayList<T>();
Gson gson = new Gson();
JsonArray array= json.getAsJsonArray();
Iterator<JsonElement> iterator = array.iterator();
while(iterator.hasNext()){
JsonElement json2 = (JsonElement)iterator.next();
T object = (T) gson.fromJson(json2, (Class<?>)type);
newArray.add(object);
}
return newArray;
}
}
Run Code Online (Sandbox Code Playgroud)
JSONParsingTest.java:
public class JSONParsingTest {
List<World> worlds;
@Test
public void grantThatDeserializerWorksAndParseObjectArrays(){
String worldAsString = "{\"worlds\": [" +
"{\"name\":\"name1\",\"id\":1}," +
"{\"name\":\"name2\",\"id\":2}," +
"{\"name\":\"name3\",\"id\":3}" +
"]}";
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Collection.class, new CollectionDeserializer());
Gson gson = builder.create();
Object decoded = gson.fromJson((String)worldAsString, JSONParsingTest.class);
assertNotNull(decoded);
assertTrue(JSONParsingTest.class.isInstance(decoded));
JSONParsingTest decodedObject = (JSONParsingTest)decoded;
assertEquals(3, decodedObject.worlds.size());
assertEquals((Long)2L, decodedObject.worlds.get(1).getId());
}
}
Run Code Online (Sandbox Code Playgroud)
World.java:
public class World {
private String name;
private Long id;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
Run Code Online (Sandbox Code Playgroud)
在对象数组中转换
Gson gson=new Gson();
ElementType [] refVar=gson.fromJson(jsonString,ElementType[].class);
Run Code Online (Sandbox Code Playgroud)
转换为帖子类型
Gson gson=new Gson();
Post [] refVar=gson.fromJson(jsonString,Post[].class);
Run Code Online (Sandbox Code Playgroud)
要将其读作对象列表,可以使用 TypeToken
List<Post> posts=(List<Post>)gson.fromJson(jsonString,
new TypeToken<List<Post>>(){}.getType());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
104471 次 |
| 最近记录: |