Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

json - Extract parameters and their values from query string in Java

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());
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...