Transform String into Array - Groovy

2

I have String as follows:

[["155","123RET"],["156","124RET"]]

In other words, I need to add an item in each of them, so I need them in the end to be as follows:

[["1","155","123RET"],["2","156","124RET"]]

I need to convert this subArrays original to string so I can change them according to my needs.

I tried the following:

def array = Eval.me(suprimentoRetEstoque)

And my return was like this:

[[155, 123RET],[156, 124RET]]

But I can not get through these subArrays, is there any way to convert a string to array other than this array ?

    
asked by anonymous 21.11.2017 / 17:54

2 answers

4

Use / p>

Using Eval is not the best solution in most cases , and this solution will fail when the data type changes, it is not adaptable.

So, it's best to use JsonSlurper :

import groovy.json.JsonSlurper

def arrayString = "[10, 1, 9]"
def arrayList = new JsonSlurper().parseText(ids)

println "${arrayList[0]}"; // Mostra o primeiro item do array (que no caso é outro array)

To scroll the Array and the subArrays use .each :

arrayList.each { array ->
    array.each { valor ->
        // Aqui voce manipula o valor de cada subArray
        println "${valor}";
    };
};

That in java "pure" would be:

for (Array array : list) {
    for (String valor : array) {
        // Aqui voce manipula o valor de cada subArray
        System.out.println(valor);
    }
}
    
21.11.2017 / 20:01
2

With the help of @LucasHenrique I was able to solve my question of converting a string into an array and I was able to add something in the subArrays, my final code looks like this:

def numEstoqueManual = numeroEstoqueRetornoManual as Integer
def arrayRetorno = new JsonSlurper().parseText(suprimentoRetEstoque)
def lista = []
def listaFinal = []

arrayRetorno.each { array ->

    lista.add(numEstoqueManual)
    array.each { valor ->
        lista.add(valor)
    };
    numEstoqueManual++
    listaFinal.add(lista)
    lista = []
};

Again thanks for the help Lucas

    
22.11.2017 / 12:11