10

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"}

2 Answers 2

11

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"}
Sign up to request clarification or add additional context in comments.

4 Comments

This method may work. However I'm not sure why you're iterating over each character when you can just call paramIn.replaceAll("whatever", "whatever else") once each for the ampersand and the equals sign.
@rufism I must agree with you, I do really do not remember why I did the for loop, but here I am updating my solution, and it still works. BTW I vote up for your answer as well.
I think .replaceAll("\\+", " ") should be included?
@Ghostff thanks this method is just simple converter, it can be manipulated in different directions. If in your case it helps to add \\+ please do it the way that it fits best. If there is another reason I did not catch please explain.
3

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

1 Comment

I don't think there is any 'standard' solution for this issue, however there are a few ways of going about this. Take a look at JSONObject, IOUtils, and/or GSON. Check out this question and this question as well as they talk about ways of grabbing potentially large URL strings and creating JSON from them.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.