2017-01-14 62 views
0

我試圖解析該FCM消息和構建Java對象FCM消息使用GSON

FirebaseMessageService解析到Java類的有效載荷進行解析如下

// Check if message contains a data payload. 
if (remoteMessage.getData().size() > 0) { 
    Log.v(TAG, "Message data payload: " + remoteMessage.getData()); 

    Map<String, String> params = remoteMessage.getData(); 
    JSONObject object = new JSONObject(params); 
    Log.v(">>JSON_OBJECTTOSTRING ", object.toString()) 

檢索到的字符串被{"message":"[{\"mName\":\"Milk\",\"mUnit\":\"1 Litre\"},{\"mName\":\"curd\",\"mUnit\":\"1 Litre\"}]"}

上述字符串在另一個類解析如下

JsonObject jo = new JsonParser().parse(order).getAsJsonObject(); 
JsonArray jsonArray = jo.getAsJsonArray("message"); 
itemList = new Gson().fromJson(jsonArray, GroceryItem[].class); 

收到這個錯誤而檢索所引起的一個數組:

java.lang.ClassCastException:com.google.gson.JsonPrimitive不能轉換到com.google.gson.JsonArray

能你幫我?

+0

你的json字符串是錯誤的。 Json字符串應該像這樣:{\「message \」:[{\「mName \」:\「Milk \」,\「mUnit \」:\「1 Liter \」},{\「mName \」: 「curd \」,\「mUnit \」:\「1 Liter \」}]}'。我用這個json字符串解析。有用。 – atiqkhaled

回答

0

您的JSON包含一個編碼爲字符串的內部JSON。如果仔細查看message屬性,則會發現應該再次解析它。比方說:

final Gson gson = new Gson(); 
final JsonParser jsonParser = new JsonParser(); 
// get the outer root the way you already do 
final JsonObject outerRoot = jsonParser.parse(JSON).getAsJsonObject(); 
// pick the inner JSON as a string 
final String innerJson = outerRoot.get("message").getAsJsonPrimitive().getAsString(); 
// and now you can parse it as a regular JSON 
final JsonArray innerRoot = jsonParser.parse(innerJson).getAsJsonArray(); 
final GroceryItem[] groceryItems = gson.fromJson(innerRoot, GroceryItem[].class); 
out.println(Arrays.toString(groceryItems)); 

和輸出(假定GroceryItem.toString()方法以某種方式定義):

[GroceryItem {MNAME = '牛奶',mUnit = '1升'},GroceryItem {MNAME = 'curd',mUnit ='1 Liter'}]

+0

這工作,謝謝 – Nimble

相關問題