2013-09-04 27 views
8

ile aşağıdaki modeli seri ediyorum: fooElements dizgeler olan 'bir', 'iki' ve 'üç içeriyorDizgeleştirme dizi Jackson

class Foo { 

    private List<String> fooElements; 
} 

edin.

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

Nasıl böyle bakmak alabilirsiniz:

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

Örnek gösterebilir misiniz? Bunu nasıl yapıyorsunuz? Bu gerçekten garip. –

cevap

8

Özel bir sıralayıcı ekleyerek çalışıyorum:

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

Eğer Jackson kullanıyorsanız, aşağıdaki basit örnek benim için çalıştı JSON bir dizesi içerir.

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

    public Foo() { 
    } 

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

başına bir Java uygulaması kullanarak:

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

    } 

} 

Çıktı:

{ "fooElements": [ "bir", "iki

Foo sınıfı tanımla "," üç "]}