2014-04-25 6 views
8

Ich habe ein JSON-Objekt, das einige Nullwerte enthalten kann. Ich benutze ObjectMapper aus com.fasterxml.jackson.databind, um mein JSON-Objekt als String zu konvertieren.Enable Object Mapper Die Methode writeValueAsString enthält Nullwerte

private ObjectMapper mapper = new ObjectMapper(); 
String json = mapper.writeValueAsString(object); 

Wenn mein Objekt ein beliebiges Feld enthält, die einen Wert als null enthält, dann wird das Feld nicht im String enthalten, die von writeValueAsString kommt. Ich möchte, dass mein ObjectMapper mir alle Felder in der Zeichenfolge gibt, selbst wenn ihr Wert null ist.

Beispiel:

object = {"name": "John", "id": 10} 
json = {"name": "John", "id": 10} 

object = {"name": "John", "id": null} 
json = {"name": "John"} 
+0

Können Sie ein Beispiel zeigen? Jackson sollte Dinge auf "null" serialisieren. –

+0

@SotiriosDelimanolis, Beispiel hinzugefügt. – LINGS

+0

Es hängt von den Anmerkungen zum Typ ab oder wie der Mapper konfiguriert ist, siehe zB [http://stackoverflow.com/questions/11757487/how-to-tell-jackson-to-ignore-a-field -during-serialisierung-wenn-sein-Wert-ist-null). –

Antwort

5

Jackson null Felder null standardmäßig serialisiert werden soll. Siehe das folgende Beispiel

public class Example { 

    public static void main(String... args) throws Exception { 
     ObjectMapper mapper = new ObjectMapper(); 
     mapper.configure(SerializationFeature.INDENT_OUTPUT, true); 
     String json = mapper.writeValueAsString(new Test()); 
     System.out.println(json); 
    } 

    static class Test { 
     private String help = "something"; 
     private String nope = null; 

     public String getHelp() { 
      return help; 
     } 

     public void setHelp(String help) { 
      this.help = help; 
     } 

     public String getNope() { 
      return nope; 
     } 

     public void setNope(String nope) { 
      this.nope = nope; 
     } 
    } 
} 

druckt

{ 
    "help" : "something", 
    "nope" : null 
} 

Sie brauchen nichts Besonderes zu tun.

0

Include.ALWAYS arbeitete für mich.

objectMapper.setSerializationInclusion(com.fasterxml.jackson.annotation.JsonInclude.Include.ALWAYS); 

Andere mögliche Werte für Enthalten sind

  • Include.NON_DEFAULT
  • Include.NON_EMPTY
  • Include.NON_NULL
Verwandte Themen