简体   繁体   English

Java将Json数组转换为类型列表<T>

[英]Java convert Json array to typed List<T>

I have a webservice that sends a typed arraylist which I capture via HttpResponse like so: 我有一个Web服务发送一个类型化的数组列表,该数组列表是通过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?

The array that's being sent from the webservice looks like this: 从Web服务发送的数组如下所示:

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

And comes out in this format: 并以以下格式显示:

[{"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 

My question is, how can I convert this back into an arraylist ( ArrayList<Item> ) There is already an Item class present in the client application. 我的问题是,如何将其转换回arraylist( ArrayList<Item> )客户端应用程序中已经存在一个Item类。

I've read examples about the Gson library but it seems it's not included anymore when compiling in API 17. 我已经阅读了有关Gson库的示例,但似乎在API 17中进行编译时不再包含该示例。

What would be the easiest approach? 最简单的方法是什么?

Download and include GSON jar from here in your project if using Eclipse. 如果使用Eclipse,请从此处下载GSON jar并将其包含在您的项目中。

If using Android Studio then open your build.gradle and add the below to your dependencies block. 如果使用Android Studio,则打开build.gradle并将以下内容添加到dependencies块中。 Or again you can choose not to use maven and simply drop the jar in your lib folder. 或者再次,您可以选择不使用Maven,只需将jar放到lib文件夹中。

compile 'com.google.code.gson:gson:2.2.4'

Next, use GSON to construct a list of items. 接下来,使用GSON构造项目列表。 Make sure you have your Item.java class with same member names as in the JSON response 确保您的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());

Make sure you handle the exceptions appropriately. 确保适当处理异常。

You could use Jackson to parse the incoming JSON. 您可以使用Jackson解析传入的JSON。 ( Quick introduction ) 快速介绍

If you already have a Class with the appropriate properties, it can be as easy as something like this: 如果您已经拥有一个具有适当属性的Class,则可以像下面这样简单:

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

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

See this for more information. 请参阅以获取更多信息。

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

I think you should using json-simple library to parse string Json to JsonObject and convert to simple data type. 我认为您应该使用json-simple库将字符串Json解析为JsonObject并转换为简单数据类型。 Example: 例:

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

Get each element JSONObject in JSONArray, then parse it to simple data type: 获取JSONArray中的每个元素JSONObject,然后将其解析为简单数据类型:

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

You can use Gson like many users said, here is an example of a RESTfull client using Gson : 您可以像许多用户所说的那样使用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;
    }

}

The usage will be something like this: new RestRequest("myserver.com/rest/somewebservice", SomeClass.class, Arrays.asList(new BasicValuePair("postParameter", "someParameterValue"))); 用法将如下所示: new RestRequest("myserver.com/rest/somewebservice", SomeClass.class, Arrays.asList(new BasicValuePair("postParameter", "someParameterValue")));

Where SomeClass.class will be Recipe[].class in your case. 在您的情况下, SomeClass.class将是Recipe[].class Also check this question to properly handle server side errors. 还要检查问题以正确处理服务器端错误。

Man, google is your friend! 伙计,谷歌是你的朋友! A quick search for "android json" or "android json parse" gives you some nice tutorials like this one or this here . 快速搜索“ android json”或“ android json parse”会为您提供一些类似教程或教程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM