2012-07-18 5 views
0

나는 다음과 같은 형태로 일부 JSON이 있습니다Jackon ObjectMapper를 사용하여 다른 필드와 함께 클래스 배열에 매핑합니까?

"items": [ 
{ 
    "id": 1, 
    "text": "As a user without a subscription, I get a choice of available ones.", 
    "status": "finished", 
    "tags": [ 
    { 
     "id": 1234, 
     "name": "feature=subs" 
    }, 
    { 
     "id": 1235, 
     "name": "epic=premium" 
    } 
    ] 
}, 
{ 
    "id": 2, 
    ... 

더 필드가 있습니다하지만 명확성을 위해 그들을 ommitted있다. ID, 텍스트, 상태 및 태그 목록이있는 스토리 클래스에 각 스토리를 매핑하려고합니다. 프로젝트가 스토리의 ArrayList를 간단하고, JsonToStory는 다음과 같은 방법

public Project JsonToProject(byte[] json) throws JsonParseException, JsonMappingException, IOException 
{ 
    ObjectMapper mapper = new ObjectMapper(); 
    mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); 

    JsonNode rootNode = mapper.readValue(json, JsonNode.class); 
    int storyCount = rootNode.get("totalItems").asInt(); 
    ArrayNode itemsNode = (ArrayNode) rootNode.get("items"); 

    Project project = new Project(); 

    for (int i = 0; i < storyCount; i++) 
    { 
     Story story = JsonToStory(rootNode.get(i)); 
     project.addStory(story); 
    } 
return project; 
} 

:

public Story JsonToStory(JsonNode rootNode) throws JsonParseException, JsonMappingException, IOException 
{ 
    ObjectMapper mapper = new ObjectMapper(); 
    mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); 
    Story story = mapper.readValue(rootNode, Story.class); 
    return story; 
} 

다음과 같이 이야기 클래스는 다음과 같습니다

나는 그것이 다음 사용하여 제대로 작동있어
public class Story { 

    private int id; 
    private String text = new String(); 
    private String status = new String(); 
    private final List<Tag> tags = new ArrayList<Tag>(); 

    public void setId(int i) 
    { 
     id = i; 
    } 

    public void setText(String s) 
    { 
     text = s; 
    } 

    public void setStatus(String s) 
    { 
     status = s; 
    } 

    public void setTags(Tag[]) 
    { 
     ??? 
    } 
} 

get 메소드 및 인쇄 방법. 태그 클래스는 단순히 두 개의 문자열 필드를 포함합니다.

Tag 객체의 arraylist를 생성하기 위해 setTags 메소드를 구성하는 방법을 알지 못하고 도움이 될만한 것을 찾을 수 없었습니다.

감사합니다.

답변

0

태그를 final로 표시 했으므로 설정자가 태그를 설정하지 못할 수 있습니다. 이 시도 할 수 있습니다 :

public class Story { 
    private int id; 
    private String text = new String(); 
    private String status = new String(); 
    private List<Tag> tags; 
    public void setTags(List<Tag> tags){ 
     this.tags = tags; 
    } 

또는

public class Story { 
    private int id; 
    private String text = new String(); 
    private String status = new String(); 
    private Tag[] tags; 
    public void setTags(Tag[] tags){ 
     this.tags = tags; 
    }