我想達到以下XML使用的字段類型:FasterXML系列化沒有XML
<model>
<entry>
<key>A</key>
<value>1</value>
</entry>
<entry>
<key>B</key>
<value>2</value>
</entry>
</model>
最近POJO模型我已經通過我的代碼試驗得到如下:
import com.fasterxml.jackson.annotation.JsonRootName;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import static com.google.common.collect.Lists.newArrayList;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import org.junit.Test;
public class InsPersonFormTest {
@JsonRootName("model")
public static class Model extends ArrayList<Entry> {
public Model(List<Entry> entries) { super(entries); }
public List<Entry> getEntry() { return this; }
}
public static class Entry {
String key;
String value;
public Entry(String key, String value) {
this.key = key;
this.value = value;
}
public String getKey() { return key; }
public String getValue() { return value; }
}
@Test
public void shouldSendPostRequest() throws JsonProcessingException {
Model model = new Model(newArrayList(new Entry("A", "1"), new Entry("B", "2")));
ObjectMapper xmlMapper = new XmlMapper();
String xml = xmlMapper.writeValueAsString(model);
assertThat(xml, equalTo(
"<model>"
+ "<entry><key>A</key><value>1</value></entry>"
+ "<entry><key>B</key><value>2</value></entry>"
+ "</model>"));
}
}
但它給了我
預計:
"<model><entry><key>A</key><value>1</value></entry><entry><key>B</key><value>2</value></entry></model>"
但:是
"<model><item><key>A</key><value>1</value></item><item><key>B</key><value>2</value></item></model>"
我怎樣才能改變item
到entry
或使用simpliest POJO結構更適合Map<String, String>
場?
由於''標記中的雙重包裝,我已經使'Model'類成爲'ArrayList'的子類。如果我完全按照您的建議做了所有事情,那麼不幸的是這種情況會再次出現。下面是一個輸出:'甲 乙 '。正如你可以看到''標籤再次翻倍。 –
ytterrr
@ytterrr你說得對。爲此增加了解決方案。 –
'@ JacksonXmlElementWrapper'是使它工作的關鍵註釋。謝謝。 – ytterrr