Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse a query string parameter to java object

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.

like image 464
Sonrobby Avatar asked Jun 13 '26 07:06

Sonrobby


2 Answers

Inspired by @bruno.braga, here's a way using Apache http-components. You leverage all the parsing corner cases:

List<NameValuePair> params = 
    URLEncodedUtils.parse("http://example.com/?" + queryString, Charset.forName("UTF-8"));

That'll give you a List of NameValuePair objects that should be easy to work with.

like image 199
matt burns Avatar answered Jun 14 '26 21:06

matt burns


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.

like image 43
bruno.braga Avatar answered Jun 14 '26 19:06

bruno.braga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!