0

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.

2 Answers 2

7

If your class has nothing more than what you posted, then there shouldn't be a problem using Gson's toJson(Object src, Type typeOfSrc) directly on your ArrayList :

Type listType = new TypeToken<ArrayList<TeamData>>() {}.getType();
String json = gson.toJson(mTeamDataList, listType);

The reason for that, is that your TeamData class has only generic fields.

Of course, if you want the "keys" to appear in your JSON, you should add the @SerializedName annotation on your class members.

Then, to send the data using your HttpUrlConnection, replace the line where you declare your out variable by :

OutputStreamWriter wr= new OutputStreamWriter(urlConnection.getOutputStream());
wr.write(json);
Sign up to request clarification or add additional context in comments.

6 Comments

So I could make a loop and convert each object in the array to a json string using that method, correct? But how would I make the json string that represents all the data in the array, rather than just one object at a time?
Ok thanks, that helps but how could I then send that json string to be read by the php script?
Would this work: OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream()); out.write(jsonString.getBytes()); ? I read that it's better to use OutputStream rather than OutputStreamWriter. Not sure if this will affect the php script though.
One more thing, if I add the @SerializedName annotation to my class members, would I put in parentheses the same name as the member variable or the actual column name that is in the database? I really appreciate the help!
You can put whatever you want in the parentheses. All that matters is that your php script on the other end interprets it the correct way, and stores it in the database the correct way. If you are using a NoSQL database, then it might make sense to use the same name as the database columns. But this is your choice
|
1

Use the class some think like this,

import com.google.gson.annotations.SerializedName;

import java.util.ArrayList;

/**
 * @author Krish
 */
public class TeamDataList {

    @SerializedName("mTeamDataList")
    private ArrayList<TeamData> mTeamDataList;

    public TeamDataList(ArrayList<TeamData> teamDataList) {
        this.mTeamDataList = teamDataList;
    }

    public class TeamData {
        @SerializedName("mFullName")
        String mFullName;
        @SerializedName("mShortName")
        String mShortName;
        @SerializedName("mLeague")
        String mLeague;

        //constructor, getters and setters are here
    }

}

And use this this method for serializing,

public static String toJson(Object object) {
        Gson gson = new Gson();
        return gson.toJson(object);
    }

2 Comments

How to do the same when you don't have name of the array as in mTeamDataList?
@ChinmoyPanda Use the above answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.