I have this output in Json list and I want use the Values of this list in my app
val dataOfTestToJson = Gson().toJson(maps)
//I want this
E = 2 0 2 1
I = 2 0
// this is output
[{"Q1":"E_2"},{"Q2":"E_0"},{"Q3":"E_2"},{"Q4":"I_2"},{"Q5":"I_0"},{"Q6":"E_1"}]
I want to get For example E in String and -2 Use it as a number in the formula.How can I extract each of these entities and place them in the variables(E and I)?
CodePudding user response:
I'm not entirely sure if this is what you mean. But if it's the case that you want to add up all E_ values into a variable and all I_ into another one you could do it with regex without the need of making any lists or maps or other objects and just use the string you got.
For example like this:
val response = """[{"Q1":"E_2"},{"Q2":"E_0"},{"Q3":"E_2"},{"Q4":"I_2"},{"Q5":"I_0"},{"Q6":"E_1"}]"""
val eRegex = Regex("E_(\\d )")
val iRegex = Regex("I_(\\d )")
val e = eRegex.findAll(response).map { it.groupValues[1].toInt() }.sum()
val i = iRegex.findAll(response).map { it.groupValues[1].toInt() }.sum()
e
will be 5 and i
will be 2 in this case