aw123
aw123

Reputation: 273

get Values from Json List java

I have a SpringBootApplication with REST-MVC like following Code examples: I have a Service that looks like this:

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

My REST-Controller looks like this:

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

Then I want to access the values of the "variables" like tcpident, etc.

My output is like:

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"}]

This I get if I do GET-Request on: http://localhost:8080/calls

like in following method:

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

How can I access to tcpident, requestid, and so on ?

I tried to make a Post-Request, but I got a NullPointerException. My Post Method looks like:

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

Error Message Edited:

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]

Upvotes: 0

Views: 185

Answers (1)

Milgo
Milgo

Reputation: 2767

Since you are using Spring Boot you should consider to use 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()

Please also provide a default constructor for your Call class.

You can also use RestTemplate so send a POST call.

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

Upvotes: 1

Related Questions