-3

I have this String response from server:

[{"name":"Abe","msg":"Hello, this is my message","age":33,"height":1.75},{"name":"Ben","msg":"I love play guitar :) ","age":18,"height":1.8} ...

And I have to arrange this response in an ArrayList<MyUser>

At the moment I'm using the following code:

String s[] = myresponse.split("\n|\\W");
String temp = "";
for(String z : s) {
   temp += z + "\n";
}

s = temp.split("\n+");
temp = "";
for(String z : s) {
   temp += z + " ";
}
Log.d("MyActivity", temp);

But it is a bit tricky and I lose all the non-word character in the msg "column", which I should save as a String, and the . in the height "column", which i need to save as a float value in the MyUser class.

So, is there a easiest way to split this string using .split method an RegEx or I should write my own method to do this? Thanks.

MyUser

public class MyUser {
    private String name, msg;
    private int age;
    private float height;


    public Friends(String name, String msg, int age, float height) {
        this.name = username;
        this.msg = msg;
        this.age = age;
        this.height = height;
    }
}
Gian
  • 13
  • 4
  • 9
    The string actually looks like valid JSON. You should consider using a JSON parser to deserialize, e.g. GSON or Jackson. – Henrik Aasted Sørensen Dec 13 '17 at 15:16
  • Use default JSONObject from Android or GSON, a library from Google https://github.com/google/gson – Camilo Ortegón Dec 13 '17 at 15:29
  • 1
    Thank you for all your answers, I'm new with Android and I didn't know nothing about Gson, or any other Libraries that do the same things, thanks again and sorry for the duplicate – Gian Dec 13 '17 at 15:40

1 Answers1

0

you can use the Gson to achieve this

public List<MyUser> getList(String stringJson){
  List<MyUser> myUser = null;
  Gson gson = new Gson();
  Type type = new TypeToken<List<MyUser>>() {}.getType();
  myUser = gson.fromJson(stringJson, type);
  return myUser;
}
vikas kumar
  • 10,447
  • 2
  • 46
  • 52