2016-03-07 97 views
-1

我想解析這個即將到來的REST API調用響應的JSON。你能幫我解析它作爲鍵值對嗎?在Java中沒有對象名解析JSON

對象名稱不存在。還有嵌套。記錄之間似乎沒有新的界限。

目標是提取這些數據並將其加載到數據庫中。

[ 
    { 
     "cc_emails":["[email protected]"], 
     "fwd_emails":[], 
     "reply_cc_emails":["[email protected]"], 
     "fr_escalated":false, 
     "spam":false, 
     "email_config_id":6000038087, 
     "group_id":6000110481, 
     "priority":1, 
     "requester_id":6010410791, 
     "responder_id":6002817857, 
     "source":1, 
     "company_id":null, 
     "status":2, 
     "subject":"fare", 
     "to_emails":["[email protected]"], 
     "product_id":null, 
     "id":45043, 
     "type":null, 
     "due_by":"2016-03-12T08:58:02Z", 
     "fr_due_by":"2016-03-08T08:58:02Z", 
     "is_escalated":false, 
     "description":"Dear xyze Team,\r\n\r\nWhy r u increased fair again and againasas0mail.gmail.com</a>.<br>\n", 
     "custom_fields": 
     { 
      "category":null, 
      "issue":null, 
      "route_id":null, 
      "phone_number":null, 
      "department":null, 
      "booking_id":null 
     }, 
     "created_at":"2016-03-07T08:58:02Z", 
     "updated_at":"2016-03-07T08:58:03Z", 

// ...... repeat 

} 
] 
+1

你有沒有嘗試過任何東西呢?# – nafas

回答

0

使用gson,你可以很簡單地做到這一點。

做一類的JSON像匹配字段:

public class Example { 
     private List<String> cc_emails; 
     private List<String> fwd_emails; 
     private List<String> reply_cc_emails; 
     private Boolean fr_escalated; 
     private Boolean spam; 
     private Integer email_config_id; 
     ... 
     private CustomFields custom_fields; 
     private String created_at; 
     private String updated_at; 

    } 

然後,你需要做的另一映射自定義字段

public class CustomFields { 

    private String category; 
    ... 


} 

而且使用JSON可以解析它像這個:

Type type = new TypeToken<Collection<Example>>(){}.getType(); 
new Gson().fromJson(json,type); 

你必須exson向Gson這是一個列表,如果它是一個單一的對象它會是這樣:

new Gson().fromJson(json,Example.class); 

這是我的aproach通常需要,也是在日期的java.sql.Timestamp類也可能會分析它,你將需要雖然嘗試。

+0

謝謝你讓它變得如此簡單。 :-) 我在一個類中定義了第一層結構,然後使用Map來代替customFields的類。 (i = 0; i

+0

您還應該檢查是否有空值,因爲您是從其他源解析json。但因爲你是通過全地圖迭代,試試這個: '的(一個String:gson.get(I).getCustom_fields()值()){ ... }' 如果有興趣在這兩個鍵和值你必須使用這個: '(Map.Entry Tiago