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"}
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
URLDecoder
URLEncoder
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"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With