我認爲這將是一個簡單的問題。JSON編組/解組包含對象列表的對象(Java,JSON/Jackson)
我有一個簡單的結構,類「人」,其中包含一個「SimplePerson」對象的列表。該Persons.java看起來是這樣的:
package jsontests;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName (value="persons")
public class Persons {
@JsonProperty("person")
private List< SimplePerson> l;
public Persons(List<SimplePerson> pl) {
this.l = pl;
}
public Persons() {
this.l = new ArrayList<>();
}
public List<SimplePerson> getL() {
return this.l;
}
public void setL(List<SimplePerson> l) {
this.l = l;
}
}
與 「SimplePerson.java」 看起來是這樣的:
package jsontests;
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName (value="person")
public class SimplePerson {
String name;
String firstname;
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the firstname
*/
public String getFirstname() {
return firstname;
}
/**
* @param firstname the firstname to set
*/
public void setFirstname(String firstname) {
this.firstname = firstname;
}
}
我用這個代碼塊創建這些對象和馬歇爾他們:
package jsontests;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
public class JsonListTest {
public static void main(String[] args) {
JsonListTest var = new JsonListTest();
var.run();
}
private void run() {
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
Persons cl = new Persons();
SimplePerson first = new SimplePerson();
first.setName("Schmidt");
first.setFirstname("Peter");
cl.getL().add(first);
SimplePerson second = new SimplePerson();
second.setName("Smith");
second.setFirstname("George");
cl.getL().add(second);
String s = null;
try {
s = mapper.writeValueAsString(cl);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
System.out.println(s);
}
}
不出所料
結果:
{
"persons" : {
"person" : [ {
"name" : "Schmidt",
"firstname" : "Peter"
}, {
"name" : "Smith",
"firstname" : "George"
} ]
}
}
在我看來,它寫道:「我們有一個叫做人的對象,其中包含一個叫做人的對象。這個人物對象包含一組由名字/名字對組成的對象。「這一切對我來說都是完全正確的,而且它正是代碼
不幸的是,我從客戶處收到的信息看起來有點不同。
{
"persons": [
{
"person": {
"name" : "Schmidt",
"firstname": "Peter"
}
},{
"person": {
"name" : "Smith",
"firstname": "George"
}
}
]
}
在我看來,這讀起來有點不同:「我們有一個叫person的對象,它包含一個數組。該數組的第一個和第二個元素是名爲person的對象,它們由名稱/名字對組成。
一樣的,但不同:-)我花了一天的時間找到一種方式來消費我得到的輸入 - 而我沒有成功。改變我的課堂結構沒有任何問題 - 說服消費者提供不同的JSON的機會非常小。
任何想法?謝謝!
如果您有json數據,您可以非常輕鬆地創建pojo -http://www.jsonschema2pojo.org/ –
我將從Persons對象中刪除根名稱並將列表重命名爲「persons」,然後將alwaysWrap設置爲true在SimplePerson的根名稱註釋上,最後禁用映射器上的wrap root值功能。 這樣你可能會說:「一個集合類型屬性的對象稱爲」個人「,其中包含(強類型?)」人「(類型?)對象...」 – Zsolt
@德里克 - 非常感謝 - 這真的很有幫助。 – Ishiido