【问题标题】:get Values from Json List java从 Json 列表 java 中获取值
【发布时间】:2020-11-25 11:06:58
【问题描述】:

我有一个带有 REST-MVC 的 SpringBootApplication,如下代码示例: 我有一个看起来像这样的服务:

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 等“变量”的值。

我的输出是这样的:

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

如果我在 http://localhost:8080/calls 上执行 GET-Request 会得到此信息

如下方法:

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等?

我试图发出一个 Post-Request,但我得到了 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]

【问题讨论】:

    标签: java json spring-boot rest


    【解决方案1】:

    由于您使用的是 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);
    

    【讨论】:

    • 我尝试了我的 Get() 方法。现在得到错误:无法启动该过程。 :类型定义错误:[简单类型,类com.example.workflow.Call];嵌套异常是 com.fasterxml.jackson.databind.exc.InvalidDefinitionException:无法构造 com.example.workflow.Call 的实例(没有创建者,如默认构造,存在):无法从对象值(没有基于委托或基于属性的创建者)反序列化 [来源:(PushbackInputStream); line: 1, column: 3] (通过引用链: java.lang.Object[][0]) 因为我用 Camunda Tasklist 启动 Process,也许你有想法?
    • 我解决了这个问题,在我的 Call.java 类中添加了一个默认构造函数,就像在这个问题中提到的那样:stackoverflow.com/questions/53191468/… 你能给我一个示例代码(比如使用 resttemplate 吗?)方法?
    • 添加了一个帖子示例。另请阅读baeldung.com/rest-template 之类的教程。
    • 感谢这对我帮助很大!但现在我的 Post 方法出现 NullPointerexception:我在上面的问题中添加了我的 Post 方法。有什么想法吗?
    • 你必须定义restTemplate。请仔细阅读您的堆栈跟踪。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-20
    • 1970-01-01
    • 2020-03-11
    • 2020-11-28
    相关资源
    最近更新 更多