2016-08-13 97 views
1

JSON字符串麻煩轉換JSON數組成POJO的使用POJO的陣列

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

Order類

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以外的東西還是我錯誤地構建這種

回答

0

有兩個問題在你的代碼:

  1. 您的JSON的根元素是「訂單」,但這個班級沒有這個名字的財產。嘗試改變你的模型或只是從JSON中刪除元素。
  2. 「orderItem」屬性的名稱不匹配。它是班級中的複數,但在JSON中單數。

總結一下,下面的JSON可以在沒有任何代碼改變的情況下工作。

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

此外,「計數」,因爲它出現在JSON好像是數字,所以你可能想的OrderItem.count的類型更改爲intjava.lang.Integer