从Json列表中获取值 Java

huangapple go评论76阅读模式
英文:

get Values from Json List java

问题

以下是您提供的代码的翻译部分:

我有一个SpringBootApplication类似于以下代码示例
我有一个看起来像这样的Service

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-Controller看起来像这样

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

然后我想访问"variables"变量的值如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",&quot

<details>
<summary>英文:</summary>

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&lt;Call&gt; callList = new ArrayList&lt;&gt;(Arrays.asList(new Call(&quot;33333301&quot;,&quot;61&quot;,&quot;Test&quot;,
                &quot;Test&quot;,&quot;Test&quot;,&quot;Test&quot;,&quot;Test&quot;,&quot;Test&quot;,&quot;Test&quot;,&quot;Test&quot;,
                &quot;Test&quot;,&quot;Test&quot;,&quot;Test&quot;,&quot;Test&quot;,&quot;Test&quot;,&quot;Test&quot;,&quot;Test&quot;,
                &quot;Test&quot;,&quot;Test&quot;,&quot;Test&quot;,&quot;Test&quot;,&quot;Test&quot;,&quot;Test&quot;,
                &quot;Test&quot;,&quot;Test&quot;,&quot;Test&quot;,&quot;Test&quot;,&quot;Test&quot;,&quot;Test&quot;,
                &quot;Test&quot;,&quot;Test&quot;,&quot;Test&quot;),new Call(&quot;33333302&quot;,&quot;61&quot;,&quot;Test&quot;,
                &quot;Test&quot;,&quot;Test&quot;,&quot;Test&quot;,&quot;Test&quot;,&quot;Test&quot;,&quot;Test&quot;,&quot;Test&quot;,
                &quot;Test&quot;,&quot;Test&quot;,&quot;Test&quot;,&quot;Test&quot;,&quot;Test&quot;,&quot;Test&quot;,&quot;Test&quot;,
                &quot;Test&quot;,&quot;Test&quot;,&quot;Test&quot;,&quot;Test&quot;,&quot;Test&quot;,&quot;Test&quot;,
                &quot;Test&quot;,&quot;Test&quot;,&quot;Test&quot;,&quot;Test&quot;,&quot;Test&quot;,&quot;Test&quot;,
                &quot;Test&quot;,&quot;Test&quot;,&quot;Test&quot;)));
    
        public List&lt;Call&gt; 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(&quot;/calls&quot;)
        public List&lt;Call&gt; getAllCalls(){
            return callService.getAllCallList();
        }
    
        @PostMapping(&quot;/calls&quot;)
        public void addCall(@RequestBody Call call){
            callService.addCall(call);
        }
    }

Then I want to access the values of the &quot;variables&quot; like tcpident, etc.

My output is like:

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

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(&quot;http://localhost:8080/calls&quot;);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod(&quot;GET&quot;);
                conn.setRequestProperty(&quot;Accept&quot;, &quot;application/json&quot;);
    
                if (conn.getResponseCode() != 200) {
                    throw new RuntimeException(&quot;Failed : HTTP error code : &quot;
                            + conn.getResponseCode());
                }
    
                BufferedReader br = new BufferedReader(new InputStreamReader(
                        (conn.getInputStream())));
    
                String output;
                System.out.println(&quot;Output from Server .... \n&quot;);
                while ((output = br.readLine()) != null) {
                    System.out.println(&quot;Output from GetCall&quot;+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&lt;String, String&gt; parameters = new LinkedMultiValueMap&lt;&gt;();
            //headers.setContentType(MediaType.APPLICATION_JSON);
            parameters.add(&quot;tcpident&quot;,&quot;1&quot;);
            parameters.add(&quot;requestid&quot;,&quot;2&quot;);
            parameters.add(&quot;mclass&quot;,&quot;3&quot;);
            parameters.add(&quot;mno&quot;,&quot;4&quot;);
            parameters.add(&quot;errorstate&quot;,&quot;5&quot;);
            parameters.add(&quot;datalength&quot;,&quot;6&quot;);
            parameters.add(&quot;resourceid&quot;,&quot;1&quot;);
            parameters.add(&quot;ono&quot;,&quot;2&quot;);
            parameters.add(&quot;opos&quot;,&quot;3&quot;);
            parameters.add(&quot;wpno&quot;,&quot;23&quot;);
            parameters.add(&quot;opno&quot;,&quot;ddsds&quot;);
            parameters.add(&quot;bufno&quot;,&quot;d&quot;);
            parameters.add(&quot;bufpos&quot;,&quot;ds&quot;);
            parameters.add(&quot;carrierid&quot;,&quot;dsdd&quot;);
            parameters.add(&quot;palletid&quot;,&quot;dsd&quot;);
            parameters.add(&quot;palletpos&quot;,&quot;dsd&quot;);
            parameters.add(&quot;pno&quot;,&quot;dsd&quot;);
            parameters.add(&quot;oposid&quot;,&quot;ds&quot;);
            parameters.add(&quot;stepno&quot;,&quot;dsd&quot;);
            parameters.add(&quot;maxrecords&quot;,&quot;dsd&quot;);
            parameters.add(&quot;boxid&quot;,&quot;dsd&quot;);
            parameters.add(&quot;boxpos&quot;,&quot;dsd&quot;);
            parameters.add(&quot;mainopos&quot;,&quot;dsds&quot;);
            parameters.add(&quot;eltno&quot;,&quot;dsd&quot;);
            parameters.add(&quot;cno&quot;,&quot;dsd&quot;);
            parameters.add(&quot;boxpno&quot;,&quot;ds&quot;);
            parameters.add(&quot;palletpno&quot;,&quot;dsd&quot;);
            parameters.add(&quot;aux1int&quot;,&quot;ds&quot;);
            parameters.add(&quot;aux2int&quot;,&quot;ds&quot;);
            parameters.add(&quot;aux1dint&quot;,&quot;dsdsd&quot;);
            parameters.add(&quot;aux2dint&quot;,&quot;dsd&quot;);
            parameters.add(&quot;mainpno&quot;,&quot;dsod&quot;);
            HttpEntity&lt;MultiValueMap&lt;String, String&gt;&gt; request = new HttpEntity&lt;&gt;(parameters);
            ResponseEntity&lt;Call[]&gt; response = restTemplate.postForEntity(&quot;http://localhost:8080/calls&quot;, request, Call[].class);
        }


Error Message Edited:

    org.springframework.web.client.HttpClientErrorException$BadRequest: 400 : [{&quot;timestamp&quot;:&quot;2020-08-05T13:05:24.741+0000&quot;,&quot;status&quot;:400,&quot;error&quot;:&quot;Bad Request&quot;,&quot;message&quot;:&quot;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]

</details>


# 答案1
**得分**: 1

由于您正在使用Spring Boot您应考虑使用RestTemplate

```java
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();
// 现在可以像output[0].getTcpIdent()这样使用output

请还为您的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);
英文:

Since you are using Spring Boot you should consider to use RestTemplate.

RestTemplate restTemplate = new RestTemplate();
ResponseEntity&lt;Call[]&gt; response = restTemplate.getForEntity(&quot;http://localhost:8080/calls&quot;, Call[].class);
if (response.getStatusCode() != HttpStatus.OK) {
throw new RuntimeException(&quot;Failed : HTTP error code : &quot;
+ 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&lt;String, String&gt; parameters = new LinkedMultiValueMap&lt;&gt;();
parameters.add(&quot;id&quot;, &quot;1&quot;);
HttpEntity&lt;MultiValueMap&lt;String, String&gt;&gt; request = new HttpEntity&lt;&gt;(parameters);
ResponseEntity&lt;Object[]&gt; response = restTemplate.postForEntity(&quot;http://localhost:8080/calls&quot;, request, Call[].class);

huangapple
  • 本文由 发表于 2020年8月5日 17:35:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/63262355.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定