使用GSON将FCM消息解析为Java类

时间:2017-01-14 14:26:40

标签: java parsing gson deserialization

我正在尝试解析FCM消息并构建java对象

FirebaseMessageService中,有效负载的解析如下

// 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

你可以帮助我吗?

1 个答案:

答案 0 :(得分: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 ='Milk',mUnit ='1 Liter'},GroceryItem {mName ='curd',mUnit ='1 Liter'}]