33

I'm trying to use Jackson to convert a HashMap to a JSON representation.

However, all the ways I've seen involve writing to a file and then reading it back, which seems really inefficient. I was wondering if there was anyway to do it directly?

Here's an example of an instance where I'd like to do it

public static Party readOneParty(String partyName) {
  Party localParty = new Party();
  if(connection==null) {
    connection = new DBConnection();
  } try {
    String query = "SELECT * FROM PureServlet WHERE PARTY_NAME=?";
    ps = con.prepareStatement(query);
    ps.setString(1, partyName);
    resultSet = ps.executeQuery();
    meta = resultSet.getMetaData();
    String columnName, value;
    resultSet.next();
    for(int j=1;j<=meta.getColumnCount();j++) { // necessary to start at j=1 because of MySQL index starting at 1
      columnName = meta.getColumnLabel(j);
      value = resultSet.getString(columnName);
      localParty.getPartyInfo().put(columnName, value); // this is the hashmap within the party that keeps track of the individual values. The column Name = label, value is the value
    }
  }
}

public class Party {

  HashMap <String,String> partyInfo = new HashMap<String,String>();

  public HashMap<String,String> getPartyInfo() throws Exception {
    return partyInfo;
  }
}

The output would look something like this

"partyInfo": {
  "PARTY_NAME": "VSN",
  "PARTY_ID": "92716518",
  "PARTY_NUMBER": "92716518"
}

So far every example I've come across of using ObjectMapper involves writing to a file and then reading it back.

Is there a Jackson version of Java's HashMap or Map that'll work in a similar way to what I have implemented?

davnicwil
  • 28,487
  • 16
  • 107
  • 123
  • Possible duplicate of [Convert Map to JSON using Jackson](http://stackoverflow.com/questions/29340383/convert-map-to-json-using-jackson) – Suma Nov 14 '16 at 09:19

2 Answers2

70

Pass your Map to ObjectMapper.writeValueAsString(Object value)

It's more efficient than using StringWriter, according to the docs:

Method that can be used to serialize any Java value as a String. Functionally equivalent to calling writeValue(Writer,Object) with StringWriter and constructing String, but more efficient.

Example

import org.codehaus.jackson.map.ObjectMapper;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class Example {

    public static void main(String[] args) throws IOException {
        Map<String,String> map = new HashMap<>();
        map.put("key1","value1");
        map.put("key2","value2");

        String mapAsJson = new ObjectMapper().writeValueAsString(map);
        System.out.println(mapAsJson);
    }
}
davnicwil
  • 28,487
  • 16
  • 107
  • 123
  • gave you the check because it gave a more efficient way of doing it –  Jul 23 '13 at 21:45
  • @davnicwil I think it should be `new ObjectMapper().writeValueAsString(map)` – Allan Ruin Mar 27 '14 at 19:50
  • Spot on, this did it for me. Thanks! – Stephen Rodriguez Mar 02 '15 at 19:59
  • I'm having an issue with newlines not being replaced with `\n` (which is how JS `JSON.stringify` handles newlines). Is `ObjectMapper().writeValueAsString()` supposed to handle newlines? If not, then its not really converting it to JSON. – Seth McClaine Jan 09 '18 at 23:02
  • 1
    @SethMcClaine `it's not really converting it to JSON` - I'm not sure what you mean by this, JSON doesn't require newlines. Are you talking about pretty printing the JSON output just to make it more human readable? This is a slightly separate concern, the question is about converting a HashMap to a JSON string - you may or may not want to pretty print that JSON. Also, `JSON.stringify` in JS doesn't insert newlines into the JSON output either, unless you optionally specify an indentation as the third arg. – davnicwil Jan 11 '18 at 09:41
  • @davnicwil I've managed to find a resolution to my question, but my concern was that when using `ObjectMapper().writeValueAsString(map)` if you were to put the output into a JSP, it will break on `\n` because it is invalid json because the jsp evaluates the `\n`. The resolution I found was to use `Gson().toJson(map)`. This encodes tags (` – Seth McClaine Jan 11 '18 at 22:05
8

You can use a StringWriter.

package test;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

public class StringWriterExample {

    private static ObjectMapper objectMapper = new ObjectMapper();

    public static void main(String[] args) throws IOException {

        Map<String,String> map = new HashMap<>();
        map.put("key1","value1");
        map.put("key2","value2");

        StringWriter stringWriter = new StringWriter();

        objectMapper.writeValue(stringWriter, map);

        System.out.println(stringWriter.toString());
    }
}

produces

{"key2":"value2","key1":"value1"}
Emerson Farrugia
  • 11,153
  • 5
  • 43
  • 51