Parse a query string parameter to java object

Sonrobby picture Sonrobby · Nov 8, 2012 · Viewed 12.5k times · Source

I have query string like that:

ObjectGUId=1abcde&ObjectType=2&ObjectTitle=maximumoflife&Content=racroi&TimeStamp=2012-11-05T17:20:06.056

And I have Java Object:

LogObject{
    private String ObjectGUId;
    private String ObjectType;
    private String ObjectTitle;
    private String Content;
    private String TimeStamp;
}

So i want to parse this query string to this java Object.

I've searched and read many question but not gotten correct answer yet.

Show me what can solve this problem.

Answer

bruno.braga picture bruno.braga · Oct 15, 2013

If you do not really need to push the querystring into your own class (you might want that though), instead of parsing it manually, you could use the URLDecoder, as @Sonrobby has commented:

String qString = "ObjectGUId=1abcde&ObjectType=2&ObjectTitle=maximumoflife";
Uri uri = Uri.parse(URLDecoder.decode("http://dummy/?" + qString, "UTF-8"));
if (uri != null) {
    for(String key: uri.getQueryParameterNames()) {
        System.out.println("key=[" + key + "], value=[" + uri.getQueryParameter(key) + "]");
    }
}            

The "dummy" looks dirty but it is required if what you only have is the querystring values (qString). If you have the complete URL, just pass it directly to the URLDecoder, and you are done.