Java将Json数组转换为类型化列表<t> </t>

时间:2013-10-28 18:32:57

标签: 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);
// 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?

从webservice发送的数组如下所示:

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"));

以这种格式出现:

[{"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>) 客户端应用程序中已存在Item类。

我已经阅读了关于Gson库的示例,但在API 17中进行编译时似乎不再包含它。

最简单的方法是什么?

6 个答案:

答案 0 :(得分:1)

如果使用Eclipse,请在项目中从here下载并包含GSON jar。

如果使用Android Studio,请打开build.gradle并将以下内容添加到dependencies块中。或者你可以选择不使用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());

确保妥善处理例外情况。

答案 1 :(得分:0)

您可以使用Jackson来解析传入的JSON。 (Quick introduction

如果您已经有一个具有适当属性的类,它可以像这样简单:

public class Items {
    private List<Item> items;
    // getter+setter
}

ObjectMapper mapper = new ObjectMapper();
Items = mapper.readValue(src, Items.class);

有关详细信息,请参阅this

答案 2 :(得分:0)

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);

答案 3 :(得分:0)

我认为您应该使用json-simple库将字符串Json解析为JsonObject并转换为简单数据类型。 例如:

JSONArray arrJson = (JSONArray) parser.parse("String json");

在JSONArray中获取每个元素JSONObject,然后将其解析为简单数据类型:

long recipeCategory = (long) jsonObject.get("recipeCategory");

答案 4 :(得分:0)

您可以像许多用户一样使用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;
    }

}

用法将是这样的: new RestRequest("myserver.com/rest/somewebservice", SomeClass.class, Arrays.asList(new BasicValuePair("postParameter", "someParameterValue")));

在您的情况下,SomeClass.classRecipe[].class。另请检查this问题以正确处理服务器端错误。

答案 5 :(得分:-1)

男人,谷歌是你的朋友!快速搜索“android json”或“android json parse”可以为你提供一些很好的教程,如this onethis here

相关问题