Search code examples
androiddatabasesplitserverseparator

How separate data obtained from server by unique separator?


I want to ask if there's some way to split data obtained from server by some unique separator.

Here is an example:

I use AsyncTask to send data to server and then I use echo command for sending those back to my application and in onPostExecute I split these data to needed result.

So let's say, that I want to get from server data for Name and Surname, so echo command on server will look like this: echo $name."&".$surname;

And then in onPostExecute I will split this data by "&" separator, but problem occurs when user writes to name or surname my separator "&" which I am using for split.

How can I avoid this issue?


Solution

  • Look into using JSON. It's a life saver for sending data. Android has native JSON support using a JSONObject.

    Documentation

    It essentially provides a formatter and parser for information placed within the object that are then accessible via keywords.

    To write a json:

    public String writeJSON() {
      JSONObject object = new JSONObject();
      try {
        object.put("name", "John");
        object.put("surname", "Doe");
        return object.toString();
      } catch (JSONException e) {
        e.printStackTrace();
        return null;
      }
    } 
    

    This will return a string that looks like:

    {"name":"John","surname":"Doe"}
    

    To read:

    public void readJSON(String jsonString){
        try {
            JSONObject object = new JSONObject(jsonString);
            String name = object.getString("name");
            String surname = object.getString("surname");
        } catch (JSONException e){
            e.printStackTrace();
        }
    }