Java将Json数组转换为类型化列表<;T>;
我有一个Web服务,它发送一个类型化的arraylist,我通过HttpResponse捕获它,如下所示:Java将Json数组转换为类型化列表<;T>;,java,android,json,list,Java,Android,Json,List,我有一个Web服务,它发送一个类型化的arraylist,我通过HttpResponse捕获它,如下所示: // create GET request HttpGet httpGet = new HttpGet("http://localhost:8084/MinecraftRestServer/webresources/Items"); // execute GET request HttpResponse response = client.execute(httpGet); // chec
// create GET request
HttpGet httpGet = new HttpGet("http://localhost:8084/MinecraftRestServer/webresources/Items");
// execute GET request
HttpResponse response = client.execute(httpGet);
// check response
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // response OK
// retreive response
List<Recipe> recipesList = new ArrayList<Recipe>();
HttpEntity jsonObj = response.getEntity();
//What's next?
并以以下格式发布:
[{"recipeCategory":11,"recipeImageID":"diamond_ingot","recipeDescription":"Diamond ingot","recipeLocations":"0,0,0,0,0,0,0,0,1","usedImages":"air,diamond_ore","recipeID":1},{"recipeCategory":11,"recipeImageID":"iron_ingot","recipeDescription":"Iron ingot","recipeLocations":"0,0,0,0,0,0,0,0,1","usedImages":"air,iron_ore","recipeID":2},{"recipeCategory":11,"recipeImageID":"gold_ingot","recipeDescription":"Gold ingot","recipeLocations":"0,0,0,0,0,0,0,0,1","usedImages":"air,gold_ore","recipeID":3},{"recipeCategory":11,"recipeImageID":"diamond_ore","recipeDescription":"Diamond ore","recipeLocations":"0,0,0,0,0,0,0,0,1","usedImages":"air,wooden_pickaxe","recipeID":4},{"recipeCategory":11,"recipeImageID":"iron_ore","recipeDescription":"Iron ore","recipeLocations":"0,0,0,0,0,0,0,0,1","usedImages":"air,wooden_pickaxe","recipeID":5},{"recipeCategory":11,"recipeImageID":"gold_ore","recipeDescription":"Gold ore","recipeLocations":"0,0,0,0,0,0,0,0,1","usedImages":"air,wooden_pickaxe","recipeID":6},{"recipeCategory":2,"recipeImageID":"diamond_boots","recipeDescription":"Boots (Diamond)","recipeLocations":"0,0,0,1,0,1,1,0,1","usedImages":"air,diamond_ingot","recipeID":7},{"recipeCategory":2,"recipeImageID":"gold_boots","recipeDescription":"Boots (Gold)","recipeLocations":"0,0,0,1,0,1,1,0,1","usedImages":"air,gold_ingot","recipeID":8},{"recipeCategory":2,"recipeImageID":"iron_boots","recipeDescription":"Boots (Iron)","recipeLocations":"0,0,0,1,0,1,1,0,1","usedImages":"air,iron_ingot","recipeID":9},{"recipeCategory":2,"recipeImageID":"diamond_leggings","recipeDescription":"Leggings (Diamond)","recipeLocations":"1,1,1,1,0,1,1,0,1","usedImages":"air,diamond_ingot","recipeID":10},{"recipeCategory":2,"recipeImageID":"gold_leggings","recipeDescription":"Leggings (Gold)","recipeLocations":"1,1,1,1,0,1,1,0,1","usedImages":"air,gold_ingot","recipeID":11},{"recipeCategory":2,"recipeImageID":"iron_leggings","recipeDescription":"Leggings (Iron)","recipeLocations":"1,1,1,1,0,1,1,0,1","usedImages":"air,iron_ingot","recipeID":12},{"recipeCategory":2,"recipeImageID":"diamond_chestplate","recipeDescription":"Chestplate (Diamond)","recipeLocations":"1,0,1,1,1,1,1,1,1","usedImages":"air,diamond_ingot","recipeID":13},{"recipeCategory":2,"recipeImageID":"gold_chestplate","recipeDescription":"Chestplate (Gold)","recipeLocations":"1,0,1,1,1,1,1,1,1","usedImages":"air,gold_ingot","recipeID":14},{"recipeCategory":2,"recipeImageID":"iron_chestplate","recipeDescription":"Chestplate (Iron)","recipeLocations":"1,0,1,1,1,1,1,1,1","usedImages":"air,iron_ingot","recipeID":15},{"recipeCategory":2,"recipeImageID":"diamond_helmet","recipeDescription":"Helmet (Diamond)","recipeLocations":"1,1,1,1,0,1,0,0,0","usedImages":"air,diamond_ingot","recipeID":16},{"recipeCategory":2,"recipeImageID":"gold_helmet","recipeDescription":"Helmet (Gold)","recipeLocations":"1,1,1,1,0,1,0,0,0","usedImages":"air,gold_ingot","recipeID":17},{"recipeCategory":2,"recipeImageID":"iron_helmet","recipeDescription":"Helmet
我的问题是,如何将其转换回arraylist(arraylist
)
客户端应用程序中已存在一个Item类
我已经阅读了有关Gson库的示例,但在API 17中编译时似乎不再包含它
最简单的方法是什么?伙计,谷歌是你的朋友!快速搜索“android json”或“android json parse”可以为您提供一些不错的教程,如或。您可以使用这些教程来解析传入的json。() 如果您已经有了一个具有适当属性的类,那么它可以像下面这样简单:
recipesList.add(new Item(1, 11, "diamond_ingot", "Diamond ingot",
"0,0,0,0,0,0,0,0,1", "air,diamond_ore"));
recipesList.add(new Item(2, 11, "iron_ingot", "Iron ingot",
"0,0,0,0,0,0,0,0,1", "air,iron_ore"));
public class Items {
private List<Item> items;
// getter+setter
}
ObjectMapper mapper = new ObjectMapper();
Items = mapper.readValue(src, Items.class);
公共类项目{
私人清单项目;
//getter+setter
}
ObjectMapper mapper=新的ObjectMapper();
Items=mapper.readValue(src,Items.class);
有关更多信息,请参阅。我认为您应该使用json简单库将字符串json解析为JsonObject并转换为简单数据类型。
Step 1 : Item obj=new Item;
Step 2: Parse the json formar for example here :
[[Example1][1]
Step 3: while parsing put ur values in obj :
obj.recipeCategory=value1;
Step 4: insret ur obj into arraylist:
arrayList.add(obj);
例如:
获取JSONArray中的每个元素JSONObject,然后将其解析为简单数据类型:
long recipeCategory = (long) jsonObject.get("recipeCategory");
如果使用Eclipse,请从项目中下载并包括
GSON
jar
如果使用Android Studio,请打开build.gradle
并将以下内容添加到依赖项
块中。或者,您也可以选择不使用maven,只需将jar放在lib文件夹中
compile 'com.google.code.gson:gson:2.2.4'
接下来,使用GSON
构建项目列表。
确保您的Item.java
类具有与JSON
响应中相同的成员名称
List<Recipe> recipesList = new ArrayList<Recipe>();
HttpEntity jsonObj = response.getEntity();
String data = EntityUtils.toString(entity);
Log.d("TAG", data);
Gson gson = new GsonBuilder().create();
recipesList = gson.fromJson(data, new TypeToken<List<Item>>() {}.getType());
List recipesList=new ArrayList();
HttpEntity jsonObj=response.getEntity();
字符串数据=EntityUtils.toString(实体);
Log.d(“标签”,数据);
Gson Gson=new GsonBuilder().create();
recipesList=gson.fromJson(数据,newTypeToken(){}.getType());
请确保适当地处理异常。您可以使用
Gson
正如许多用户所说,下面是一个使用Gson
的RESTfull客户端示例:
public class RestRequest {
Gson gson = new Gson();
public <T> T post(String url, Class<T> clazz,
List<NameValuePair> parameters) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
// Add your data
httppost.setEntity(new UrlEncodedFormEntity(parameters));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
StringBuilder json = inputStreamToString(response.getEntity()
.getContent());
T gsonObject = gson.fromJson(json.toString(), clazz);
return gsonObject;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
// Fast Implementation
private StringBuilder inputStreamToString(InputStream is)
throws IOException {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
}
// Return full string
return total;
}
}
公共类重新请求{
Gson Gson=新的Gson();
公共T帖子(字符串url、类clazz、,
列表参数){
//创建一个新的HttpClient和Post头
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(url);
试一试{
//添加您的数据
setEntity(新的UrlEncodedFormEntity(参数));
//执行HTTP Post请求
HttpResponse response=httpclient.execute(httppost);
StringBuilder json=inputStreamToString(response.getEntity()
.getContent());
T gsonObject=gson.fromJson(json.toString(),clazz);
返回gsonObject;
}捕获(例外e){
e、 printStackTrace();
}
返回null;
}
//快速实现
私有StringBuilder inputStreamToString(InputStream为)
抛出IOException{
字符串行=”;
StringBuilder总计=新StringBuilder();
//在InputStream周围包装一个BufferedReader
BufferedReader rd=新的BufferedReader(新的InputStreamReader(is));
//读取响应直到结束
而((line=rd.readLine())!=null){
合计.追加(行);
}
//返回完整字符串
返回总数;
}
}
用法如下所示:
new RestRequest(“myserver.com/rest/somewebservice”、SomeClass.class、Arrays.asList(新的基本值对(“后参数”、“someParameterValue”)))代码>
其中SomeClass.class
将是Recipe[].class
。还要检查问题以正确处理服务器端错误。u的意思是说要将json解析为arraylist?@MT8是的,它是一个类型化的arraylist,类项为typecreate a arraylist instance,解析json,存储在arraylist中,问题是什么?我已经阅读了有关Gson库的示例,但在API 17中编译时似乎不再包含它了。
这是错误的GSON
从未与android api一起包含。如果使用Android Studio
@RobbieVercammen,您需要下载jar或将其添加到build.gradle
中的dependencies
块看看我的答案。它展示了如何将JSON字符串解析为一个类型化列表。更多的是评论,更多的是回答感谢批评者。。。对于教程,它们非常有用。如果你不知道你要用谷歌搜索什么,用谷歌搜索是不容易的。我猜我在谷歌上搜索得太具体了。我正在尝试你的方法!我已经添加了gson库,但是现在我遇到了networkonmain线程异常。等等:)您不应该在主线程上执行任何网络操作。如果您在修复NetworkOnMainThreadException
时遇到问题,那么已经有很多答案了-我已经找到了答案,我用一个新的runable包围了它,并设法让列表在填充内容之前等待。但是,在本地主机上调用我的Web服务时,我仍然被拒绝连接。我认为在模拟器或设备上使用本地主机将不起作用。您可能需要使用承载WebDevice的计算机的IP地址。不,是缺少权限!它成功了,我已经从网络服务中得到了我的数据。谢谢。顺便说一句,如果您为专用设备打开端口,它在本地主机上也可以工作;)Inputstream到string是我的第一种方法,但Varuns的答案更准确。谢谢你的意见
public class RestRequest {
Gson gson = new Gson();
public <T> T post(String url, Class<T> clazz,
List<NameValuePair> parameters) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
// Add your data
httppost.setEntity(new UrlEncodedFormEntity(parameters));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
StringBuilder json = inputStreamToString(response.getEntity()
.getContent());
T gsonObject = gson.fromJson(json.toString(), clazz);
return gsonObject;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
// Fast Implementation
private StringBuilder inputStreamToString(InputStream is)
throws IOException {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
}
// Return full string
return total;
}
}