我正在嘗試決議一個 json 資料檔案,該檔案在兩個不同的 ArrayList 中有一個單一物件:
{
"TA": [
{
"firstname": "John",
"lastname": "Smith"
},
{
"firstname": "Jane",
"lastname": "Doe"
}
],
"Student": [
{
"firstname": "John",
"lastname": "Smith"
},
{
"firstname": "Kevin",
"lastname": "White"
}
]
}
我當前的決議方法只是為每個物件創建一個新的 Person 物件并將它們添加到每個 List 物件中,但我希望我的 Person 物件 John Smith 只是一個被“TA”串列和“Student”串列參考的單一物件。我怎么能去做這件事?
uj5u.com熱心網友回復:
如果您想降低記憶體使用量,您可以使用靜態工廠方法來實習實體。假設您使用杰克遜:
class Person {
private static Map<Person, Person> cache = new HashMap<>();
@JsonCreator
public static Person create(
@JsonProperty("firstname") String firstname,
@JsonProperty("lastname") String lastname) {
Person person = new Person(firstname, lastname);
return cache.computeIfAbsent(person, Function.identity());
}
final String firstname;
final String lastname;
private Person(String firstname, String lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
@Override
public boolean equals(Object o) {
return o instanceof Person
&& Objects.equals(((Person)o).firstname, this.firstname)
&& Objects.equals(((Person)o).lastname, this.lastname);
}
@Override
public int hashCode() {
return Objects.hash(this.firstname, this.lastname);
}
}
uj5u.com熱心網友回復:
TA和Student list是兩個不同的list。如果您定義每個串列并用相同的物件(人)填充它們,是的,它們將指向相同的物件。那就是面向物件的方法。
決議 Json 并期望在兩個陣列中具有相同的 person 物件是不可能的(假設決議器會創建該 person 物件)。決議器將單獨處理每個陣列,因此您的個人物件不會相同。
有一種方法可以通過在靜態類中定義 person 物件來實作。通過這種方式,您將始終獲得 person 物件的相同實體。
我你的情況,你將不得不為每個變體(名字姓氏)創建一個靜態人物物件
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/338285.html
上一篇:從JSON中選擇
下一篇:用檔案值替換json嵌套字典值
