получить значения из Json Список java - PullRequest
0 голосов
/ 05 августа 2020

У меня есть SpringBootApplication с REST- MVC, как в следующих примерах кода: У меня есть служба, которая выглядит так:

package com.example.workflow;

import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class CallService {
    private List<Call> callList = new ArrayList<>(Arrays.asList(new Call("33333301","61","Test",
            "Test","Test","Test","Test","Test","Test","Test",
            "Test","Test","Test","Test","Test","Test","Test",
            "Test","Test","Test","Test","Test","Test",
            "Test","Test","Test","Test","Test","Test",
            "Test","Test","Test"),new Call("33333302","61","Test",
            "Test","Test","Test","Test","Test","Test","Test",
            "Test","Test","Test","Test","Test","Test","Test",
            "Test","Test","Test","Test","Test","Test",
            "Test","Test","Test","Test","Test","Test",
            "Test","Test","Test")));

    public List<Call> getAllCallList() {
        return callList;
    }

    public void addCall(Call call) {
        callList.add(call);
    }
}

Мой REST-контроллер выглядит так:

package com.example.workflow;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class CallController {

    @Autowired
    private CallService callService;

    @GetMapping("/calls")
    public List<Call> getAllCalls(){
        return callService.getAllCallList();
    }

    @PostMapping("/calls")
    public void addCall(@RequestBody Call call){
        callService.addCall(call);
    }
}

Затем я хочу получить доступ к значениям «переменных», таких как tcpident, et c.

Мой результат такой:

Output from GetCall[{"tcpident":"33333301","requestid":"61","mclass":"Test","mno":"Test","errorstate":"Test","datalength":"Test","resourceid":"Test","ono":"Test","opos":"Test","wpno":"Test","opno":"Test","bufno":"Test","bufpos":"Test","carrierid":"Test","palletid":"Test","palletpos":"Test","pno":"Test","oposid":"Test","stepno":"Test","maxrecords":"Test","boxid":"Test","boxpos":"Test","mainopos":"Test","beltno":"Test","cno":"Test","boxpno":"Test","palletpno":"Test","aux1int":"Test","aux2int":"Test","aux1dint":"Test","aux2dint":"Test","mainpno":"Test"},{"tcpident":"33333302","requestid":"61","mclass":"Test","mno":"Test","errorstate":"Test","datalength":"Test","resourceid":"Test","ono":"Test","opos":"Test","wpno":"Test","opno":"Test","bufno":"Test","bufpos":"Test","carrierid":"Test","palletid":"Test","palletpos":"Test","pno":"Test","oposid":"Test","stepno":"Test","maxrecords":"Test","boxid":"Test","boxpos":"Test","mainopos":"Test","beltno":"Test","cno":"Test","boxpno":"Test","palletpno":"Test","aux1int":"Test","aux2int":"Test","aux1dint":"Test","aux2dint":"Test","mainpno":"Test"}]

Это я получаю, если сделаю GET -Запрос на: http://localhost: 8080 / вызывает

как в следующем методе:

public void get(){
        try {

            URL url = new URL("http://localhost:8080/calls");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/json");

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

            BufferedReader br = new BufferedReader(new InputStreamReader(
                    (conn.getInputStream())));

            String output;
            System.out.println("Output from Server .... \n");
            while ((output = br.readLine()) != null) {
                System.out.println("Output from GetCall"+output);
            }
            conn.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Как я могу получить доступ к tcpident, Requestid и т. Д.?

Я попытался сделать пост-запрос, но получил исключение NullPointerException. Мой метод публикации выглядит так:

public void post(){
        MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
        //headers.setContentType(MediaType.APPLICATION_JSON);
        parameters.add("tcpident","1");
        parameters.add("requestid","2");
        parameters.add("mclass","3");
        parameters.add("mno","4");
        parameters.add("errorstate","5");
        parameters.add("datalength","6");
        parameters.add("resourceid","1");
        parameters.add("ono","2");
        parameters.add("opos","3");
        parameters.add("wpno","23");
        parameters.add("opno","ddsds");
        parameters.add("bufno","d");
        parameters.add("bufpos","ds");
        parameters.add("carrierid","dsdd");
        parameters.add("palletid","dsd");
        parameters.add("palletpos","dsd");
        parameters.add("pno","dsd");
        parameters.add("oposid","ds");
        parameters.add("stepno","dsd");
        parameters.add("maxrecords","dsd");
        parameters.add("boxid","dsd");
        parameters.add("boxpos","dsd");
        parameters.add("mainopos","dsds");
        parameters.add("eltno","dsd");
        parameters.add("cno","dsd");
        parameters.add("boxpno","ds");
        parameters.add("palletpno","dsd");
        parameters.add("aux1int","ds");
        parameters.add("aux2int","ds");
        parameters.add("aux1dint","dsdsd");
        parameters.add("aux2dint","dsd");
        parameters.add("mainpno","dsod");
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(parameters);
        ResponseEntity<Call[]> response = restTemplate.postForEntity("http://localhost:8080/calls", request, Call[].class);
    }

Сообщение об ошибке отредактировано:

org.springframework.web.client.HttpClientErrorException$BadRequest: 400 : [{"timestamp":"2020-08-05T13:05:24.741+0000","status":400,"error":"Bad Request","message":"Invalid JSON input: Cannot deserialize instance of `java.lang.String` out of START_ARRAY token; nested excepti... (484 bytes)]
    at org.springframework.web.client.HttpClientErrorException.create(HttpClientErrorException.java:101) ~[spring-web-5.2.4.RELEASE.jar:5.2.4.RELEASE]
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:170) ~[spring-web-5.2.4.RELEASE.jar:5.2.4.RELEASE]
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:112) ~[spring-web-5.2.4.RELEASE.jar:5.2.4.RELEASE]
    at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63) ~[spring-web-5.2.4.RELEASE.jar:5.2.4.RELEASE]
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:782) ~[spring-web-5.2.4.RELEASE.jar:5.2.4.RELEASE]
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:740) ~[spring-web-5.2.4.RELEASE.jar:5.2.4.RELEASE]
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:674) ~[spring-web-5.2.4.RELEASE.jar:5.2.4.RELEASE]
    at org.springframework.web.client.RestTemplate.postForEntity(RestTemplate.java:449) ~[spring-web-5.2.4.RELEASE.jar:5.2.4.RELEASE]
    at com.example.workflow.PostRequestDelegate.post(PostRequestDelegate.java:85) ~[classes/:na]
    at com.example.workflow.PostRequestDelegate.execute(PostRequestDelegate.java:28) ~[classes/:na]

1 Ответ

1 голос
/ 05 августа 2020

Поскольку вы используете Spring Boot, вам следует подумать об использовании RestTemplate.

RestTemplate restTemplate = new RestTemplate();
ResponseEntity<Call[]> response = restTemplate.getForEntity("http://localhost:8080/calls", Call[].class);

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

Call[] output = response.getBody();
// now use output like output[0].getTcpIdent()

Также укажите конструктор по умолчанию для вашего класса Call.

Вы также можете использовать RestTemplate, поэтому отправьте POST звонок.

MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
        parameters.add("id", "1");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(parameters);
ResponseEntity<Object[]> response = restTemplate.postForEntity("http://localhost:8080/calls", request, Call[].class);
...