无法使用pojos数组将Json数组转换为Pojo

时间:2016-08-13 02:47:18

标签: java arrays json gson

JSON字符串

{
"order":{
  "address":{
     "city":"seattle"
  },
  "orderItem":[
     {
        "itemId":"lkasj",
        "count":2
     },
     {
        "itemId":"ldka",
        "count":3
     }
  ]
   }
}

订单类

public class Order {
private OrderItem[] orderItems;
private CustomerAddress address;

Order(OrderItem[] orderItems, CustomerAddress address ) {
    this.orderItems = orderItems;
    this.address = address;

}

public OrderItem[] getOrderItems() {
    return orderItems;
}

public void setOrderItems(OrderItem[] orderItems) {
    this.orderItems = orderItems;
}

public CustomerAddress getAddress() {
    return address;
}

public void setAddress(CustomerAddress address) {
    this.address = address;
}
}

我的OrderItem类     包com.cbd.backend.model;

import org.springframework.data.annotation.Id;

public class OrderItem {
    @Id
    private String id;
    private String itemId;
    private String count;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

unit Test that blows up

    public String getItemId() {
        return itemId;
    }

    public void setItemId(String itemId) {
        this.itemId = itemId;
    }

    public String getCount() {
        return count;
    }

    public void setCount(String count) {
        this.count = count;
    }
}

单元测试以证明问题     包com.cbd.backend.model;

import com.google.gson.Gson;
import org.junit.Test;
import static org.junit.Assert.*;
public class OrderTest {

  Gson gson = new Gson();
  @Test
    public void gsonToOrder() {
        Order order = gson.fromJson( a, Order.class );
        assertNotNull(order);
        assertNotNull(order.getOrderItems()[0]);
    }
    private final String a = "{ \"order\": { \"address\": { \"city\": \"seattle\" },\"orderItem\":[{ \"itemId\":\"lkasj\", \"count\":2 }, { \"itemId\":\"ldka\", \"count\":3 } ] } }";
}

我应该使用除gson以外的其他东西还是我构建错误的

1 个答案:

答案 0 :(得分:0)

您的代码中存在两个问题:

  1. 您的JSON的根元素是“order”,但该类没有具有此名称的属性。尝试更改模型或仅从JSON中删除元素。
  2. “orderItem”属性的名称不匹配。它在类中是复数,但在JSON中是单数。
  3. 总而言之,以下JSON无需更改代码即可运行。

    {
        "address":{
            "city":"seattle"
        },
        "orderItems":[
            {
                "itemId":"lkasj",
                "count":2
            },
            {
                "itemId":"ldka",
                "count":3
            }
        ]
    }
    

    此外,JSON中显示的“count”似乎是数字,因此您可能希望将OrderItem.count的类型更改为intjava.lang.Integer