I would like to convert the data in an ArrayList to JSON and then send it to my webserver. The list mTeamDataList is of type ArrayList<TeamData>.
The TeamData class is:
public class TeamData
{
String mFullName;
String mShortName;
String mLeague;
//constructor, getters and setters are here
}
I have a addTeamsToDB() method that is responsible for writing the data in the array to the webserver. Here is what I have so far:
public static void addTeamsToDB()
{
if(mTeamDataList.size() == 0)
return;
HttpURLConnection urlConnection = null;
String addTeamURL = "http://api.somewebsite.com/add_team.php";
try
{
Gson gson = new Gson();
URL urlObj = new URL(addTeamURL);
urlConnection = (HttpURLConnection) urlObj.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.connect();
//I believe converting to json goes here
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
assert urlConnection != null;
urlConnection.disconnect();
}
}
I found several answers on SO but they only showed basic examples of inserting one object or hard-coded data. I have not found one to convert an array of custom data-type objects to JSON using Gson.
Is there a method that does this or do I have to manually convert each item in the array through a loop?
I was following this tutorial but he's using the NameValuePairs class to achieve this. But it's deprecated so I'm not sure what to use instead.
Also, the tutorial is using the built-in JSON java library so if someone can show the Gson way instead, that would be very helpful.