3

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,

JQuery Mobile
  • 6,221
  • 24
  • 81
  • 134
  • Possibly a duplicate of http://stackoverflow.com/questions/12155800/how-to-convert-hashmap-to-json-object-in-java – Tuim Apr 08 '14 at 13:02
  • 1
    here is everything you need http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/ – nikis Apr 08 '14 at 13:02

5 Answers5

7

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

David Hofmann
  • 5,683
  • 12
  • 50
  • 78
4

You could also use Jackson, which is in Maven. And you can use it like this:

Map<String,Object> map = .... // create a map
ObjectMapper mapper = new ObjectMapper()
String jsonFromMap = mapper.writeValueAsString(map);

Note that the ObjectMapper has many other methods to read to/from objects.

I recommend it because it's easy to use, supports annotations, is production ready and used by many organizations and probably most important, is integrated in many existing framework (Spring, Jersey, RESTeasy, Camel, etc.).

I am not familiar with GSON, but there is a discussion about the two you might want to take a look at.

Community
  • 1
  • 1
Giovanni Botta
  • 9,626
  • 5
  • 51
  • 94
0

It is true that there are a lot of json parsers for java. Have a look at the json org link to read about the different json parsers available for java. Also this link provides nice and simple tutorials for different json parsers.

Personally I use simple json in applications that do not have a lot of json parsing to do and use gson for applications that are mostly based on json and hence have to do a lot of json.

anirudh
  • 4,116
  • 2
  • 20
  • 35
0

Underscore-java library can convert hash map or array list to json and vice verse.

Code example:

import com.github.underscore.U;
import java.util.*;

public class Main {

    @SuppressWarnings("unchecked")
    public static void main(String[] args) {

      Map<String, Object> map = new HashMap<String, Object>();
      map.put("1", "a");
      map.put("2", "b");

      System.out.println(U.toJson(map));

      Map<String, Object> newMap = (Map<String, Object>) U.fromJson($.toJson(map));         
      System.out.println(newMap.get("1")); // -> "a"

    }
}
Valentyn Kolesnikov
  • 2,029
  • 1
  • 24
  • 31
-2

if you need to create json from hashmap and if you dont have nested maps :-

private String createJsonString( Map<String, Object> map) {
    String jsonString = "{ ";
    Set<Map.Entry<String, Object>> entries = map.entrySet();
    for (Map.Entry<String, Object> entry : entries) {

        jsonString = jsonString + "\"" + entry.getKey() + "\"";
        jsonString += " : ";
        jsonString = jsonString + getJsonValue(entry.getValue());
        jsonString += ",  ";
    }
    int i = jsonString.lastIndexOf(",");
    jsonString = jsonString.substring(0, i);
    jsonString += " }";
    return jsonString;
}

private String getJsonValue(Object value) {
    if (value == null) {
        return "";
    } else if (value instanceof Number || value instanceof Boolean) {
        return value.toString();
    } else {
        return "\"" + value + "\"";
    }
}
leoismyname
  • 407
  • 6
  • 11