3

So let's suppose I have a string like

"param1=value1&param2={"url":"http://somesite.com?someparam=somevalue&someparam1=somevalue1"}&param3=value3"

and I need it to be:

param1: value1

param2: {"url":"http://somesite.com?someparam=somevalue&someparam1=somevalue1"}

param3: value3

What would be the best approach to parse this in Java? So far I could not found a solution with standard Java libraries, and I don't want to reinvent the wheel.

I've tried with (but it would not work if I put there only query parameters like mine):

String url = "http://www.example.com/something.html?one=11111&two=22222&three=33333";
List<NameValuePair> params = URLEncodedUtils.parse(new URI(url), "UTF-8");

for (NameValuePair param : params) {
    System.out.println(param.getName() + " : " + param.getValue());
}
9
  • url.split("=") - how about this? Commented Dec 12, 2014 at 14:28
  • 1
    Nope, it would split value from json as well Commented Dec 12, 2014 at 14:28
  • could the json part contain the '&' character ? if not, use url.split("&") Commented Dec 12, 2014 at 14:32
  • Yeap it could, I forgot to mention this, there could be a link as well with a few parameters Commented Dec 12, 2014 at 14:33
  • Is the list of parameters names known to you ? Commented Dec 12, 2014 at 14:44

1 Answer 1

5

Why don't you use something like a regex :

for example like this one ".*\\?param1=(.*)&param2=(.*)&param3=(.*)$" this works for your url sample that's why I added the .*\\? part ;)

and this will work for the first sample ("param1=value1&param2={"url":"http://somesite.com?someparam=somevalue&someparam1=somevalue1"}&param3=value3" --> param1=(.*)&param2=(.*)&param3=(.*)$

Of course if your params names aren't also something you don't know about

Sign up to request clarification or add additional context in comments.

2 Comments

Ok, I tried Pattern p = Pattern.compile(".*\\?param1=(.*)&param2=(.*)&param3=(.*)$"); then Matcher m = p.matcher(queryString); and then I tried to do a find() through matcher and it gives me no results if m.group(1).
try this: ".*param1=(.*)&param2=(.*)&param3=(.*)" assuming your string does not start with a question mark

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.