Transform String into Array - Groovy

Asked

Viewed 377 times

2

I own a String as follows:

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

In other words, in it two subArrays that I need to add an item still in each one, my need is that in the end these arrays stay as follows:

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

I need to convert this string original in a array so I can alter them according to my need.

I tried it this way:

def array = Eval.me(suprimentoRetEstoque)

And my return was like this:

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

However I am not getting through these subArrays, there is some way to convert a string in array other than that Eval.me()?

2 answers

4


Use Jsonslurper!

The use of Eval is not the best solution in most cases, besides that this solution will fail when the data type is changed, it is not adaptable.

So you better 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 traverse 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);
    }
}
  • How I can precorrer this generated array?

  • From what it says in the documentation (http://grails.asia/groovy-list-tutorial-and-examples), this object is a ArrayList of Java, I believe a forEach resolves.

  • Is that my need is just that, if you can post an answer with that I thank you ;)

  • I edited, see if it answers your doubt (I am without compiler, any error that gives can report me)

  • 1

    Forget Lucas I figured out how to do, I’ll post a reply showing how my code turned out at the end, thanks for the help :)

2

With the help of @Lucashenrique I was able to solve my problem of converting a string into an array and be able to add something in subArrays, my final code was 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 = []
};

Thanks again for the help Lucas

Browser other questions tagged

You are not signed in. Login or sign up in order to post.