杰克逊obectMapperwriteValue()不能按预期工作

时间:2018-08-04 07:27:19

标签: java json jackson

我将data.json文件反序列化为Customer.java。并尝试将Customer.java序列化为shopping.json。但是它在序列化的json数据中显示了两个列表对象(列表和食物)。应该只有一个清单(即食物)。什么地方出了错?请参见下面的代码:

ShoppingList.java
private String name;
private int amount;

public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public int getAmount() {
    return amount;
}
public void setAmount(int amount) {
    this.amount = amount;
}
@Override
public String toString() {
    return "ShoppingList [name=" + name + ", amount=" + amount + "]";
}

Customer.java

private String date;
private String name;
private String store;
@JsonProperty("food")
private List<ShoppingList> food;

public String getDate() {
    return date;
}

public void setDate(String date) {
    this.date = date;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getStore() {
    return store;
}

public void setStore(String store) {
    this.store = store;
}

public List<ShoppingList> getList() {
    return food;
}

public void setList(List<ShoppingList> list) {
    this.food = list;
}

@Override
public String toString() {
    return "Customer [date=" + date + ", name=" + name + ", store=" + store + ", food=" + food + "]";
}

Test.java

public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
    File file = new File("data.json");
    ObjectMapper mapper = new ObjectMapper();

    Customer m = mapper.readValue(file, Customer.class);
    System.out.println(m.toString());
    System.out.println(m.getList().toString());

    mapper.writeValue(new File("shopping.json"), m);

}

data.json

{
"date": "2016-07-14",
"name": "Candice",
"store": "aStore",
"food": [
    {
        "name": "eggs",
        "amount": 6
    },
    {
        "name": "Chicken",
        "amount": 1
    },
    {
        "name": "Bananas",
        "amount": 5
    },
    {
        "name": "Pasta",
        "amount": 1
    }
]

}

shopping.json

{
"date": "2016-07-14",
"name": "Candice",
"store": "aStore",
"list": [ //This list is generated extra.
    {
        "name": "eggs",
        "amount": 6
    },
    {
        "name": "Chicken",
        "amount": 1
    },
    {
        "name": "Bananas",
        "amount": 5
    },
    {
        "name": "Pasta",
        "amount": 1
    }
],
"food": [
    {
        "name": "eggs",
        "amount": 6
    },
    {
        "name": "Chicken",
        "amount": 1
    },
    {
        "name": "Bananas",
        "amount": 5
    },
    {
        "name": "Pasta",
        "amount": 1
    }
]

}

我尝试了不同的方法,但是没有运气。 预先感谢。

1 个答案:

答案 0 :(得分:1)

这可能是由于您的命名引起的。将您的getList方法和setList方法重命名为getFoodsetFood,然后重试。