2013-07-23 10 views
30

Sto provando a utilizzare Jackson per convertire una HashMap in una rappresentazione JSON.C'è un modo per convertire una mappa in una rappresentazione JSON usando Jackson senza scrivere in un file?

Tuttavia, tutti i modi che ho visto implicano la scrittura in un file e la successiva lettura, che sembra davvero inefficiente. Mi stavo chiedendo se ci fosse comunque da fare direttamente?

Ecco un esempio di un caso in cui mi piacerebbe farlo

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

L'output dovrebbe essere simile a questa

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

Finora tutti gli esempi che ho incontrato di utilizzare ObjectMapper implica la scrittura su un file e la successiva lettura.

Esiste una versione Jackson di Java HashMap o Map che funzionerà in modo simile a quello che ho implementato?

+0

Eventuali duplicati di [Convertire Mappa per JSON utilizzando Jackson] (http://stackoverflow.com/questions/29340383/convert-map-to-json-using-jackson) – Suma

risposta

63

Far passare la vostra mappa per ObjectMapper.writeValueAsString(Object value)

E 'più efficiente rispetto all'utilizzo StringWriter, according to the docs:

metodo che può essere usato per serializzare qualsiasi valore Java come una stringa. Funzionalmente equivalente a chiamare writeValue (Writer, Object) con StringWriter e costruire String, ma più efficiente.

Esempio

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); 
    } 
} 
+0

ti ha dato il controllo perché ha dato un modo più efficiente di farlo – sreya

+0

@davnicwil Penso che dovrebbe essere 'nuovo ObjectMapper(). WriteValueAsString (mappa)' –

+0

@AllanRuin Good spot - modificato :-) – davnicwil

7

È possibile utilizzare un 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()); 
    } 
} 

produce

{"key2":"value2","key1":"value1"} 
+0

+1 che funziona anche in questo modo :) – sreya

Problemi correlati