[英]JSON marshalling/unmarshalling an object that contains a list of objects (Java, JSON/Jackson)
我認為這將是一個簡單的問題。
我有一個簡單的結構,一個“ Persons”類,其中包含“ 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"
} ]
}
}
在我看來,它的意思是“我們有一個名為person的對象,其中包含一個稱為person的對象。此person-object包含由名稱/名字對組成的對象數組。” 這對我來說完全可以,這正是代碼
不幸的是,我從客戶那里收到的東西看起來有些不同。 我收到
{
"persons": [
{
"person": {
"name" : "Schmidt",
"firstname": "Peter"
}
},{
"person": {
"name" : "Smith",
"firstname": "George"
}
}
]
}
在我看來,這有點不同:“我們有一個稱為人員的對象,它包含一個數組。該數組的第一個和第二個元素是稱為人員的對象,它們由名稱/名字對組成。
相同,但是不同:-)我花了一天的時間來找到一種方法來消耗我得到的輸入-但我沒有成功。 更改我的類結構不會有問題-說服客戶提供不同JSON的機會很小。
有任何想法嗎? 謝謝!
我遵循了Derick的建議(請參閱第一個評論),並生成了所需的數據模型。 這似乎是最好的解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.