如何遍历java中对象的arrayList?

Posted

技术标签:

【中文标题】如何遍历java中对象的arrayList?【英文标题】:How to iterate over the arrayList of objects in the java? 【发布时间】:2019-04-19 11:33:37 【问题描述】:

我已经使用 Angular 将对象数组发送到 Api 以进行后期操作,这与 3 个对象的数组一起使用:

我想在 java 中这样做,所以我在 java 中将类初始化为:

SLDto.java

 public class SLDto 

        private LetterDto letterDto;
        private List<DocumentDto> documentDto;
        private List<SelectionCustomOfficeDto> selectionCustomOfficeDto;



        public SLDto() 

        
//i omitted getters and setters here
    

LetterDto.java

public class LetterDto 

  private int clkletter;
 private String inOut;
 private String inOutNo;
private String inOutDate;
private String letterIssuedSubBy;
private String letterFile;
private String representativeName;
private int assessmentNo;
private int selectionNo;


public LetterDto() 


DocumentDto.java

public class DocumentDto 

    private int docId;
    private String docName;
    private boolean checked;

    public DocumentDto() 

    

SelectionCustomOfficeDto.java

public class SelectionCustomOfficeDto 

 private int id;
 private String fromDate;
 private String  toDate;
 private int consignmentNo;
 private int selectionId;
 private int customOfficeId;
 private String custOfficeName;
 private String selectionName;

我需要将客户端对象映射到 Api,所以我使用了该方法:

 @PostMapping(value = "/letter/create")
        public String postAllOne(@RequestBody SLDto sldto ) 

            //i tried 2ways to see the json data or trace it and assign into 
         respective objects but i am not getting.I tried
        1st method
       System.out.println(sldto.getLetterDto()); //Not working 

       2nd method 
         for(LetterDto letterDto:sldto.getLetterDto()) 
                //it is not allowing me
            

            return  "success";
         

它不允许我映射为:

如何将 3json 数据分离到各自的对象中?

["inOutNo":"2018-11-12","inOutDate":"2","inOut":"AnnexOne","letterFile":null,"representativeName":null,"assessmentNo":0,"letterIssuedSubBy":null,"selectionNo":8,["docId":1,"docName":"proforma invoice","checked":true,"docId":2,"docName":"Packing list","checked":true],["customOfficeId":"1","fromDate":"2018-11-12","toDate":"2018-11-20","consignmentNo":2,"selectionId":8,"selectionName":"PCS","custOfficeName":"Bhairawa Bhansar"]] 

看到的错误是

我收到类似

的错误

"DefaultHandlerExceptionResolver : 已解决 [org.springframework.http.converter.HttpMessageNotReadableException: JSON 解析错误:无法反序列化 com.ashwin.springsecurityangular.dto.SLDto out of START_ARRAY token; 嵌套异常是 com.fasterxml.jackson.databind.exc.MismatchedInputException:不能 反序列化 com.ashwin.springsecurityangular.dto.SLDto 的实例 START_ARRAY 令牌”

【问题讨论】:

根据您的班级定义letterDto 不是collection 也不是array。是错字吗? 我收到类似“DefaultHandlerExceptionResolver: Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of com.ashwin.springsecurityangular.dto.SLDto out of START_ARRAY token; 嵌套异常是 com.fasterxml .jackson.databind.exc.MismatchedInputException:无法从 START_ARRAY 令牌中反序列化 com.ashwin.springsecurityangular.dto.SLDto 的实例” 好的 - 您的帖子中似乎存在编译时错误,因此问题是。 你能发布输入json吗 我在页首贴了一张图片,请看 【参考方案1】:

您当前的 POST 方法处理程序需要以下格式的 JSON 对象:


    "letterDto" : 
        "clkletter" : 1, 
        "inOut" : "Someting",
        ...
    ,
    "documentDto" : [
        
            "docId" : 1,
            "docName" : "Name",
            "checked" : true
         ,
        
            "docId" : 2,
            "docName" : "Name 2",
            "checked" : false
        
    ],
    "selectionCustomOfficeDto" : [
        
            "id" : 1,
            "fromDate" : "someDate,
            ...
        ,
        
            "id" : 2,
            "fromDate" : "someDate2,
            ...
        
    ]


但目前,您正在发送一个 JSON 数组:

[
    "letterDto" : <letter properties>,
    [
        
            <document properties>
        ,
        
            <document properties>
        
    ],
    [
        
            <selection custom office properties>
        
    ]
]

修复此问题后,您将能够迭代 slDto.getDocumentDtoslDto.getSelectionCustomOfficeDto,因为它们是 slDto 对象中包含的唯一集合,因此:

slDto.getSelectionCustomOfficeDto.forEach(s -> doSomething(s));

slDto.getDocumentDto.forEach(d -> doSomething(d));

你可以像这样调用Letter的方法:

slDto.getLetterDto.getId();

【讨论】:

【参考方案2】:

您好,请确保您的 JSON 请求如下所示:


    "letterDto" : 
        "clkletter" : 1,
        "inOut" : "some-string-value",
        "inOutNo" : "some-string-value",
        "inOutDate" : "some-string-value",
        "letterIssuedSubBy" : "some-string-value",
        "letterFile" : "some-string-value",
        "representativeName" : "some-string-value",
        "assessmentNo" : 1,
        "selectionNo" : 1
    ,
    "documentDto" : [
        
            "docId" : 1,
            "docName" : "some-doc-name",
            "checked" : true
        ,
        
            "docId" : 2,
            "docName" : "some-doc-name",
            "checked" : true
        ,
        
            "docId" : 3,
            "docName" : "some-doc-name",
            "checked" : true
        
    ],
    "selectionCustomOfficeDto" : [
        
            "id" : 1,
            "fromDate" : "some-date",
            "toDate" : "some-date",
            "consignmentNo" : 1,
            "selectionId" : 1,
            "customOfficeId" : 1,
            "custOfficeName" : "some-office-name",
            "selectionName" : "some-selection-name"
        ,
        
            "id" : 2,
            "fromDate" : "some-date",
            "toDate" : "some-date",
            "consignmentNo" : 1,
            "selectionId" : 1,
            "customOfficeId" : 1,
            "custOfficeName" : "some-office-name",
            "selectionName" : "some-selection-name"
        ,
        
            "id" : 3,
            "fromDate" : "some-date",
            "toDate" : "some-date",
            "consignmentNo" : 1,
            "selectionId" : 1,
            "customOfficeId" : 1,
            "custOfficeName" : "some-office-name",
            "selectionName" : "some-selection-name"
        
    ]

另外,在代码块中,

for(LetterDto letterDto:sldto.getLetterDto()) 
//it is not allowing me

这里sldto.getLetterDto() 返回单个LetterDto Object 而不是List,因此无法进行迭代。

希望对你有帮助!

【讨论】:

【参考方案3】:

你应该像下面这样发送json

 
    "letterDto" : "clkletter": "as" , // your other properties,
    "documentDto": ["docId" : 1,"docId" : 2]// your other properties inside json object
    "selectionCustomOfficeDto": ["id": 12,"id": 121]// your other properties inside json object

 

以下示例供您参考,outer 类有List&lt;Inner2&gt;List&lt;Inner3&gt;Inner1

Json 看起来像


    "inner1": "f1": "v1","f2": "v2",
    "inner2s": ["f3": "v3","f4": "v4","f3": "v5","f4": "v6"],

    "inner3s": ["f5": "v7","f6": "v8","f5": "v9","f6": "v10"]

PoJo 类

class Outer
        Inner1 inner1;
        List<Inner2> inner2s;
        List<Inner3> inner3s;

        public Inner1 getInner1() 
            return inner1;
        
        public void setInner1(Inner1 inner1) 
            this.inner1 = inner1;
        
        public List<Inner2> getInner2s() 
            return inner2s;
        
        public void setInner2s(List<Inner2> inner2s) 
            this.inner2s = inner2s;
        
        public List<Inner3> getInner3s() 
            return inner3s;
        
        public void setInner3s(List<Inner3> inner3s) 
            this.inner3s = inner3s;
        

    

     class Inner1

        String f1;
        String f2;
        public String getF1() 
            return f1;
        
        public void setF1(String f1) 
            this.f1 = f1;
        
        public String getF2() 
            return f2;
        
        public void setF2(String f2) 
            this.f2 = f2;
        



    
     class Inner2
        String f3;
        String f4;
        public String getF3() 
            return f3;
        
        public void setF3(String f3) 
            this.f3 = f3;
        
        public String getF4() 
            return f4;
        
        public void setF4(String f4) 
            this.f4 = f4;
        


    

     class Inner3
        String f5;
        String f6;
        public String getF5() 
            return f5;
        
        public void setF5(String f5) 
            this.f5 = f5;
        
        public String getF6() 
            return f6;
        
        public void setF6(String f6) 
            this.f6 = f6;
        


    

请求映射

@RequestMapping(value="/test",produces=MediaType.APPLICATION_JSON_VALUE,method= RequestMethod.POST)
    public String post(@RequestBody Outer outer) 
        LOGGER.debug("Getting the logged in cutomer details" +outer);
        Customer customer1 = new Customer("1", "customer1", "Sample@cust1.com");
        LOGGER.info("The customer details are " + customer1);
        return "done!!";
    

【讨论】:

请给反对票的理由,所以,如果有问题,可以学习。谢谢 我让我的数组看起来像这样: 抱歉 - 我没能关注你 很高兴它有帮助。 感谢您付出了太多努力@secret 超级明星,您今天为我提供了太多帮助

以上是关于如何遍历java中对象的arrayList?的主要内容,如果未能解决你的问题,请参考以下文章

eclipse中如何自动生成iterator遍历代码块吗?

java中怎么遍历list集合

Java集合框架01

在Java中遍历父类的ArrayList时使用Subclass方法

java如何对ArrayList中对象按照该对象某属性排序

list遍历陷阱分析原理