I’m not sure If the title is correct, but I’ll explain what I mean. So I’m doing a project that involves an API. I created the data classes that was need to store that information as well. Where it gets weird is actually getting the information I need. Here’s an instance of a list of information I need for the project.
"Text":"Alma Gutierrez - Alma M. Gutierrez is a fictional character on the HBO drama The Wire, played by actress Michelle Paress. Gutierrez is a dedicated and idealistic young reporter on the city desk of The Baltimore Sun."
You see, the name of the character and the description is all in a single string value. I’m usually used to name and the description being separated like this for example
Text:{
name: "Alma Gutierrez"
description:"Alma is a..."
}
So my question is, how can I manipulate the response so that I can get the name and the description separately? I am thinking maybe some sort of function that will take the string value from the JSON call and split it to a name and description values. But I’m not sure how to do that.
I’ll leave my project GitHub URL so you guys for reference. Thanks for the help.
2
Answers
To add on to what Joffery said, I actually created a variable to hold the the spited string.
Since there's only two values in the split, I can use the variable and call the index that I need for the corresponding text field.
You can use split() to split a string into parts based on a delimiter.
For instance, if you have a string containing the description as mentioned in the question, you can do the following:
(see the behaviour in this playground)
The
limit = 2
parameter ensures that you won’t miss a part of the description if it contains-
. It only splits in maximum 2 parts, so it will consider everything until the first occurrence of-
as the name, and everything after that as the description, even if it includes more occurrences of-
.Note that using the deconstruction
val (name, description) = ...
like this will fail ifsplit()
returns less than 2 parts (in other words, it will fail if the initial text doesn’t contain-
at all. It may be ok for you depending on the input you expect here.