2013-09-04 34 views
8

sto serializzazione il seguente modello:serializzazione di array con Jackson

class Foo { 

    private List<String> fooElements; 
} 

Se fooElements contiene le stringhe 'uno', 'due' e 'tre. Il JSON contiene una stringa:

{ 
    "fooElements":[ 
     "one, two, three" 
    ] 
} 

Come posso farlo sembrare come questo:

{ 
    "fooElements":[ 
     "one", "two", "three" 
    ] 
} 
+0

Puoi mostrare un esempio come lo fai? È davvero strano –

risposta

8

Ho funzionato aggiungendo un serializzatore personalizzato:

class Foo { 
    @JsonSerialize(using = MySerializer.class) 
    private List<String> fooElements; 
} 

public class MySerializer extends JsonSerializer<Object> { 

    @Override 
    public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) 
      throws IOException, JsonProcessingException { 
     List<String> fooList = (List<String>) value; 

     if (fooList.isEmpty()) { 
      return; 
     } 

     String fooValue = fooList.get(0); 
     String[] fooElements = fooValue.split(","); 

     jgen.writeStartArray(); 
     for (String fooValue : fooElements) { 
      jgen.writeString(fooValue); 
     } 
     jgen.writeEndArray(); 
    } 
} 
7

Se si utilizza Jackson, allora la seguente semplice esempio ha lavorato per me.

Definire la classe Foo:

public class Foo { 
    private List<String> fooElements = Arrays.asList("one", "two", "three"); 

    public Foo() { 
    } 

    public List<String> getFooElements() { 
     return fooElements; 
    } 
} 

Quindi, utilizzando un'applicazione Java standalone: ​​

import java.io.IOException; 

import org.codehaus.jackson.JsonGenerationException; 
import org.codehaus.jackson.map.JsonMappingException; 
import org.codehaus.jackson.map.ObjectMapper; 

public class JsonExample { 

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

     Foo foo = new Foo(); 

     ObjectMapper mapper = new ObjectMapper(); 
     System.out.println(mapper.writeValueAsString(foo)); 

    } 

} 

uscita:

{ "fooElements": [ "uno", "due "," tre "]}

Problemi correlati