在Java中将String添加到列表中

时间:2017-07-13 06:12:30

标签: java

请查看以下代码段。 我看了一下stackoverflow上提供的一些解决方案,用于将String添加到列表中。 在下面的案例中,他们的表现并不好。

@RequestMapping(value = "/rest/EmployeeDept/", method = RequestMethod.GET)
// ResponseEntity is meant to represent the entire HTTP response
public ResponseEntity<EmployeeDeptResponse> getDept()
{
    EmployeeDeptResponse deptResponse = new EmployeeDeptResponse();
    HttpStatus httpStatus;
    List<EmployeeDept> employeeDeptList = new ArrayList<EmployeeDept>();

    try {

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet getRequest = new HttpGet(
                "http://localhost:8082/rest/EmployeeDept/");
        getRequest.addHeader("accept", "application/json");
        HttpResponse response = httpClient.execute(getRequest);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : "
                    + response.getStatusLine().getStatusCode());
        }

        BufferedReader br = new BufferedReader(
                new InputStreamReader((response.getEntity().getContent())));
        String output;

        while ((output = br.readLine()) != null) {
            employeeDeptList.add(output);
        }

        deptResponse.setItems(employeeDeptList);
        httpClient.getConnectionManager().shutdown();

    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    httpStatus = HttpStatus.OK;
    return new ResponseEntity<EmployeeDeptResponse>(deptResponse,httpStatus);

}

我在while循环中收到错误,因为“add in list无法应用于java.lang.String”

“EmployeeDept”类型的列表.EmployeeDept类如下所示: -

package com.springboot.postrgres.model;

import java.io.Serializable;

public class EmployeeDept implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String dept;


public EmployeeDept() {
}

public EmployeeDept(int id, String dept) {
    this.id = id;
    this.dept = dept;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getDept() {
    return dept;
}

public void setDept(String name) {
    this.dept = dept;
}

}

在上面的代码中,我有一个列表“employeeDeptList”和一个字符串“Output”。 我需要将此字符串添加到列表中。

您是否可以提供合适的建议。

提前致谢。

4 个答案:

答案 0 :(得分:1)

employeeDeptList的类型为ArrayList<EmployeeDept>

List<EmployeeDept> employeeDeptList = new ArrayList<EmployeeDept>();
另一方面,

output属于String

类型
String output;

因此,当您执行employeeDeptList.add(output);时,您尝试向String添加employeeDeptList,而该EmployeeDept应为output

因此,您要么EmployeeDept成为output,要么重新考虑您想要做的事情。

作为建议,我将假设您的EmployeeDept dept = new EmployeeDept(parsedId, parsedDept);应包含创建EmployeeDept所需的信息。您可能希望解析该信息并创建employeeDeptList,然后将其添加到employeeDeptList.add(dept); { "name": "angular-quickstart", "version": "1.0.0", "description": "QuickStart package.json from the documentation, supplemented with testing support", "scripts": { "build": "tsc -p src/", "build:prod": "webpack -p --progress", "build:watch": "tsc -p src/ -w", "build:e2e": "tsc -p e2e/", "serve": "lite-server -c=bs-config.json", "serve:e2e": "lite-server -c=bs-config.e2e.json", "prestart": "npm run build", "start": "concurrently \"nodemon server/main.js\" \"npm run build:watch\" \"npm run serve\"", "pree2e": "npm run build:e2e", "e2e": "concurrently \"npm run serve:e2e\" \"npm run protractor\" --kill-others --success first", "preprotractor": "webdriver-manager update", "protractor": "protractor protractor.config.js", "pretest": "npm run build", "test": "concurrently \"npm run build:watch\" \"karma start karma.conf.js\"", "pretest:once": "npm run build", "postinstall": "typings install", "test:once": "karma start karma.conf.js --single-run", "lint": "tslint ./src/**/*.ts -t verbose" }, "keywords": [], "author": "", "license": "MIT", "dependencies": { "@agm/core": "^1.0.0-beta.0", "@angular/animations": "^4.2.5", "@angular/common": "~4.0.0", "@angular/compiler": "~4.0.0", "@angular/core": "~4.0.0", "@angular/forms": "~4.0.0", "@angular/http": "~4.0.0", "@angular/material": "^2.0.0-beta.7", "@angular/platform-browser": "~4.0.0", "@angular/platform-browser-dynamic": "~4.0.0", "@angular/router": "~4.0.0", "@ngui/map": "^0.18.3", "@types/googlemaps": "^3.26.14", "angular-in-memory-web-api": "~0.3.0", "angular2-image-upload": "^0.6.3", "angular2-modal": "^3.0.1", "angular2-useful-swiper": "^4.0.5", "auth0-js": "^8.7.0", "core-js": "^2.4.1", "cors": "^2.8.3", "debug-log": "^1.0.1", "express": "^4.14.0", "font-awesome": "^4.6.3", "hammerjs": "^2.0.8", "http-server": "^0.10.0", "jquery": "^2.2.4", "mysql": "^2.13.0", "ng": "0.0.0-rc6", "ng2-float-btn": "0.0.3", "ng2-page-scroll": "^4.0.0-beta.9", "ng2-parallax": "^1.0.0", "ngx-flickity": "0.0.6", "rxjs": "5.0.1", "systemjs": "0.19.40", "zone.js": "^0.8.4" }, "devDependencies": { "concurrently": "^3.2.0", "lite-server": "^2.2.2", "typescript": "~2.1.0", "typings": "^1.3.2", "webpack": "^1.13.2", "canonical-path": "0.0.2", "tslint": "^3.15.1", "lodash": "^4.16.4", "jasmine-core": "~2.4.1", "karma": "^1.3.0", "karma-chrome-launcher": "^2.0.0", "karma-cli": "^1.0.1", "karma-jasmine": "^1.0.2", "karma-jasmine-html-reporter": "^0.2.2", "protractor": "~4.0.14", "rimraf": "^2.5.4", "@types/node": "^6.0.46", "@types/jasmine": "2.5.36" }, "repository": {} }

答案 1 :(得分:0)

employeeDeptList是EmployeeDept对象的列表。您正在尝试将String添加到EmployeeDept列表中。除非您将输出变量的类型更改为EmployeeDept,否则这是不可能的。

答案 2 :(得分:0)

您的代码存在问题。

while ((output = br.readLine()) != null) {
        employeeDeptList.add(output);
    }

output是一个字符串,您尝试将其添加到List<EmployeeDept>。你不能这样做。如果要将output添加到List,则应创建一个字符串列表。像List<String>

这样的东西

如你所说,你得到的是,

  

{       &#34; 1499921014230&#34;:{           &#34; id&#34;:1499921014230,           &#34; dept&#34;:&#34; mechanics&#34;       },       &#34; 1499921019747&#34;:{           &#34; id&#34;:1499921019747,           &#34; dept&#34;:&#34; civil&#34;       }   }

如果你可以改变它,你可以尝试将它改为一个简单的对象数组,

  

[       {           &#34; id&#34;:1499921014230,           &#34; dept&#34;:&#34; mechanics&#34;       },       {           &#34; id&#34;:1499921019747,           &#34; dept&#34;:&#34; civil&#34;       }   ]

如果使用maven,则添加以下依赖项,或者只将.jar添加到lib,

<dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20090211</version> </dependency>

然后尝试这样的事情,

while ((output = br.readLine()) != null) {
    JSONArray jsonArr = new JSONArray(output);

    for (int i = 0; i < jsonArr.length(); i++) {
        JSONObject jsonObj = jsonArr.getJSONObject(i);

        String dept = jsonObj.getString("dept");
        int id = jsonObj.getInt("id");
        System.out.println("id : " + id + "    dept : " + dept);

        employeeDeptList.add(new EmployeeDept(id, dept));
    }
}

答案 3 :(得分:0)

如果您的回复是有效的json(指定标题),为什么不尝试将其映射到对象?

ObjectMapper mapper = new ObjectMapper();

//assuming your response entity content is a list of objects (json array, since you specified header 'application/json'
String jsonArray = String theString = IOUtils.toString(response.getEntity().getContent(), encoding);
employeeDeptList  = List<Employee> list = mapper.readValue(jsonString, TypeFactory.defaultInstance().constructCollectionType(List.class, employeeDeptList.class));

//assuming your response is a single object
String json = String theString = IOUtils.toString(response.getEntity().getContent(), encoding);
employeeDeptList.add(mapper.readValue(json, Employee.class));

//assuming every line of content is an object (does not really make sense)
BufferedReader br = new BufferedReader(ew InputStreamReader((response.getEntity().getContent())));
String output;

while ((output = br.readLine()) != null) {
    employeeDeptList.add(mapper.readValue(output, Employee.class));
}