2012-12-02 2 views
1

다음 코드를 참조하십시오. I는 JSON 배열로 데이터의리스트를 직렬화해야Jackson과 직렬화 된 JSON 배열의 루트 요소를 수정하는 방법

FooEntity.java :

public class FooEntity { 

String foo; 
String bar; 

public String getFoo() { 
    return foo; 
} 

public void setFoo(String foo) { 
    this.foo = foo; 
} 

public String getBar() { 
    return bar; 
} 

public void setBar(String bar) { 
    this.bar = bar; 
} 
} 

FooList.java : 여기

public class FooList { 
public List<FooEntity> fooList; 

public FooList() { 
    this.fooList = new ArrayList<FooEntity>(); 
} 

public void add(FooEntity fooEntity) { 
    this.fooList.add(fooEntity); 
} 

public List<FooEntity> getFooList() { 
    return fooList; 
} 

public void setFooList(List<FooEntity> fooList) { 
    this.fooList = fooList; 
} 
} 

I는 FooEntities 목록 작성 및 JSON으로 직렬화 :

public void fooListToJson() throws IOException { 
    FooList fooList = new FooList(); 

    FooEntity fooEntity1 = new FooEntity(); 
    fooEntity1.setBar("fooEntity1 bar value"); 
    fooEntity1.setFoo("fooEntity1 foo value"); 

    FooEntity fooEntity2 = new FooEntity(); 
    fooEntity2.setBar("fooEntity2 bar value"); 
    fooEntity2.setFoo("fooEntity2 foo value"); 

    fooList.add(fooEntity1); 
    fooList.add(fooEntity2); 

    ObjectMapper mapper = new ObjectMapper(); 
    StringWriter stringWriter = new StringWriter(); 
    final JsonGenerator jsonGenerator = mapper.getJsonFactory().createJsonGenerator(stringWriter); 

    mapper.writeValue(jsonGenerator, fooList); 

    System.out.println(stringWriter.toString()); 

그래서 출력은 followting된다

,536,
{"fooList":[{"foo":"fooEntity1 foo value","bar":"fooEntity1 bar value"},{"foo":"fooEntity2 foo value","bar":"fooEntity2 bar value"}]} 

모두 정확합니다. 단 하나만 필요합니다. 목록의 "루트"요소를 변경해야합니다. 지금은 루트 요소로 "fooList"이 있습니다.이를 변경해야합니다.

이 주제에 대한 스레드와 게시물은 거의 발견되지 않았지만 원하는만큼 정확하게 저에게 도움이되는 것은 없습니다. 솔루션은 해당 Java 클래스로 JSON을 역 직렬화 할 수있는 가능성을 유지해야합니다.

답변

1

@JsonRootName에서 필요한 것을 제공합니까?

+2

안녕하세요! 예, 작동합니다. 내가 전에 시도해 봤지만, ObjectMapper에 대해 WRAP_ROOT_VALUE를 사용하고 데이터가 포함 된 List에 대해 @JsonValue 주석을 사용하여 직렬화 된 JSON을 평준화했다 (http://stackoverflow.com/questions/13386930/). 왜 일하지 않는가?). 완전한 해결책을 가진이 요지를보십시오 : https://gist.github.com/4193797 – stibi

+0

참고 연결은 끊깁니다 – rekire

관련 문제