Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert (Parse) URL parameteres to JSON in Java

Tags:

java

json

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"}
like image 660
Maytham Avatar asked Apr 01 '15 01:04

Maytham


2 Answers

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

like image 187
rufism Avatar answered Nov 09 '22 13:11

rufism


The Solution

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 + "\"}";
}

Results

Method input:

data=data10&sensor=sensor10&type=type10

Method return output:

{"data":"data10","sensor":"sensor10","type":"type10"}
like image 10
Maytham Avatar answered Nov 09 '22 13:11

Maytham