Skip to content
Advertisement

Write HashMap to JSON in Java

I’m new to Java. I’ve been working on a project that uses Maven and Java 1.7. In my project I have a HashMap. I want to output this HashMap to JSON. What is the recommended approach at this time?

When I do a Google search, I get a lot of options (ie Jackson). However, I’m not sure what I should be using. Plus, I’d like to use a library that’s accessible via Maven.

Thank you,

Advertisement

Answer

You can use the Google GSON library.

Just add this to your pom

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.2.4</version>
</dependency>

And add this class to your project

import java.lang.reflect.Type;
import java.util.*;
import com.google.gson.*;
import com.google.gson.reflect.TypeToken;

public class JsonHelper {
    private static final Gson gson = new GsonBuilder().disableHtmlEscaping().create();
    private static final Type TT_mapStringString = new TypeToken<Map<String,String>>(){}.getType();

    public static Map<String, String> jsonToMapStringString(String json) {
        Map<String, String> ret = new HashMap<String, String>();
        if (json == null || json.isEmpty())
            return ret;
         return gson.fromJson(json, TT_mapStringString);
    }
    public static String mapStringStringToJson(Map<String, String> map) {
        if (map == null)
            map = new HashMap<String, String>();
         return gson.toJson(map);
    }
}

I guess you can figure it out how to use it

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement