0

If we have an object in groovy, for example Customer[name, email, phone] and a String in the form

String infoLine = "Stanislav,[email protected],004612345678" 

What is the easiest way to parse that string and populate the fields of that object?

(The example string we can split, that is why the question is from array of String)

1 Answer 1

2

Assuming you have a constructor

Customer(String name, String email, String phone)

You can do:

new Customer(*infoLine.split(','))

If you don't want to write a constructor, you can get Groovy to create one for you:

import groovy.transform.*

@TupleConstructor
class Customer {
    String name
    String email
    String phone
}

String infoLine = "Stanislav,[email protected],004612345678" 

new Customer(*infoLine.split(','))

Or even better, @Immutable as this makes the properties final

@Immutable
class Customer {
    String name
    String email
    String phone
}

Another option (assuming your fields are defined in the order they appear in the string, and there are no other fields), would be to generate a map of [name: 'aaa', emai... etc, and tell groovy to convert the map to a Customer like:

class Customer {
    String name
    String email
    String phone
}

String infoLine = "Stanislav,[email protected],004612345678" 

def customer = [
    Customer.declaredFields.findAll { !it.synthetic }*.name,
    infoLine.split(',')
].transpose().collectEntries() as Customer

But this feels kinda brittle, and it's probably quicker to add the annotation or constructor.

Sign up to request clarification or add additional context in comments.

3 Comments

Is it possible to skip writing the constructor? Is there even a faster way?
@StanislavIvanov gave you a few more options 😊
thanks, the second option is best as it is what I was looking for exactly. It is easier to read than the last option especially for unexperienced programmers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.