javaparsingquery-stringquerystringparameter

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.


Solution

  • Etiquette

    1. You really should be much more specific about what you have tried and why it didn't work.

    2. A proper code sample of your LogObject would really be very helpful here.

    3. Ideally, you would provide a SSCCE so others could easily test your problem themselves.

    Answer

    You can extract the name:value pairs like this:

    String toParse = "ObjectGUId=1abcde&ObjectType=2&ObjectTitle=maximumoflife&Content=racroi&TimeStamp=2012-11-05T17:20:06.056";
    String[] fields = toParse.split("&");
    String[] kv;
    
    HashMap<String, String> things = new HashMap<String, String>();
    
    
    for (int i = 0; i < fields.length; ++i)
    {
        t = fields[i].split("=");
        if (2 == kv.length)
        {
            things.put(kv[0], kv[1]); 
        }
    }
    

    I have chosen to put them into a HashMap, but you could just as easily look at the name part (kv[0]) and choose to do something with it. For example:

    if kv[0].equals("ObjectGUId")
    {
        logObject.setGUId(kv[1]); // example mutator/setter method
    }
    else if //...
    

    However, all your fields in LogObject are private and you haven't shown us any methods, so I hope you have some way of setting them from outside... bear in mind you will need to store the pairs in a data structure of some kind (as I have done with a HashMap) if you intend to intialise a LogObject with all the fields rather than setting the fields after a constructor call.

    Speaking of SSCCEs, I made one for this answer.