2015-03-30 10 views
20

Come posso convertire una mappa in un JSON valido utilizzando Jackson?Converti mappa in JSON utilizzando Jackson

lo faccio usando GSON di Google attraverso un metodo Primavera avvio REST Post ...

Ecco il RESTful Web Service:

import java.util.Map; 

import org.springframework.web.bind.annotation.RequestBody; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 
import org.springframework.web.bind.annotation.RestController; 

import com.fasterxml.jackson.core.JsonFactory; 
import com.fasterxml.jackson.core.JsonParser; 
import com.google.gson.Gson; 

@RestController 
@RequestMapping("/myservice") 
public class ValidationService {  

    @RequestMapping(value="/validate", method = RequestMethod.POST) 
    public void validate(@RequestBody Map<String, Object> payload) throws Exception { 
     Gson gson = new Gson(); 
     String json = gson.toJson(payload); 
     System.out.println(json); 
    } 
} 

Così, quando invoco utilizzando questo:

curl -H "Accept: application/json" -H "Content-type: application/json" \ 
-X POST -d '{"name":"value"}' http://localhost:8080/myservice/validate 

visualizzato il seguente stdout (questo è esattamente quello che voglio):

{"name":"value"} 

C'è un modo migliore per farlo usando Jackson invece di Gson di Google e/o sto andando del tutto nel modo sbagliato?

+0

possibile duplicato di [Jackson Vs. Gson] (http://stackoverflow.com/questions/2378402/jackson-vs-gson) –

+3

Neeraj Jain, Grazie per il commento ma: Jackson vs. Gson parla degli aspetti positivi e negativi di Jackson vs. Gson. Questo post è una domanda specifica. –

risposta

48

È possibile convertire Map-JSON utilizzando Jackson come segue:

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

String json = new ObjectMapper().writeValueAsString(payload); 
System.out.println(json); 
+0

Questo è Map to String, non JSON. Ci sarà un altro passaggio per convertire la stringa di output in tipo JSON. –

+0

@NayanWadekar questo funziona davvero, penso che ti sbagli o forse ti piacerebbe fornire qualche intuizione? –

+0

@BrunoBossola Mi dispiace, stavo pensando all'effettivo oggetto JSON, non ho visto l'output richiesto, per la rappresentazione della stringa JSON, questo è corretto. –

0

Se stai usando Jackson, meglio convertire direttamente a ObjectNode.

//not including SerializationFeatures for brevity 
static final ObjectMapper mapper = new ObjectMapper(); 

//pass it your payload 
public static ObjectNode convObjToONode(Object o) { 
    StringWriter stringify = new StringWriter(); 
    ObjectNode objToONode = null; 

    try { 
     mapper.writeValue(stringify, o); 
     objToONode = (ObjectNode) mapper.readTree(stringify.toString()); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    System.out.println(objToONode); 
    return objToONode; 
} 
1

Utilizzando Jackson, si può fare come segue:

ObjectMapper mapper = new ObjectMapper(); 
    String clientFilterJson = ""; 
    try { 
     clientFilterJson = mapper.writeValueAsString(filterSaveModel); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    }