4

I get a JSON that I want to convert to URL with parameters for example:

JSON:

{
    "id" : "27",
    "name: : "Testing name"
}

URL:

id=27&name=Testing+name

I found some solutions but only in Javascript like this:

JavaScript Object (JSON) to URL String Format

But I want to use Java, not Javascript.

Any idea how I can make the transformation with Java?

Community
  • 1
  • 1
gtx911
  • 1,189
  • 4
  • 25
  • 46

1 Answers1

5

Step 1: convert JSON into Map with some library such as jackson.

public class JacksonMapper {

    private static final ObjectMapper mapper = new ObjectMapper();

    private static final JacksonMapper INSTANCE;

    static 
    {
        INSTANCE = new JacksonMapper();
    }

    private JacksonMapper() {
        // not called
    }

    public static JacksonMapper getInstance() {

        return INSTANCE;
    }

    public Map<String, String> toMap(String jsonString) throws Exception {

        return mapper.readValue(jsonString, new TypeReference<HashMap<String, String>>(){});

   }    
}

Step 2: a) if you are using Spring, you can simply pass the Map into RestTemplate and call some of it's methods.

Step 2: b) If you are not using Spring, you could refer to Apache
UriBuilder and call method addParameter for each entry in map

Step 2: c) if you don't want to use library, you could iterate over map and build query string yourself.

John
  • 5,189
  • 2
  • 38
  • 62