Reputation: 33387
I have REST client that delivers URL as parameters. But my cloud REST infrastructure accepts only JSON format.
Is there any way to convert (parse) the URL parameters to JSON format in Java?
Example of URL parameters:
data=data10&sensor=sensor10&type=type10
to JSON format like:
{"data":"data10","sensor":"sensor10","type":"type10"}
Upvotes: 10
Views: 11882
Reputation: 33387
There was no solution out of the box, therefore it was most practical to develop a method to solve this.
Here is a Parameters to JSON converter method:
public static String paramJson(String paramIn) {
paramIn = paramIn.replaceAll("=", "\":\"");
paramIn = paramIn.replaceAll("&", "\",\"");
return "{\"" + paramIn + "\"}";
}
Method input:
data=data10&sensor=sensor10&type=type10
Method return output:
{"data":"data10","sensor":"sensor10","type":"type10"}
Upvotes: 11
Reputation: 392
Try URLEncoder/URLDecoder methods encode() and decode().
Here is a very quick example:
import java.net.URLDecoder;
import java.net.URLEncoder;
/*... further code ...*/
try {
String someJsonString = "{\"num\":2}";
String encoded = URLEncoder.encode(jsonString, "UTF-8");
System.out.println(encoded);
String decoded = URLDecoder.decode(encoded, "UTF-8");
System.out.println(decoded);
}
catch(UnsupportedEncodingException e){
e.printStackTrace();
}
And here are a few references:
How to send json data as url...
URLEncoder.encode() deprecated...
Passing complex objects in URL parameters
And finally the java docs
Upvotes: 3