使用Gson TypeToken

时间:2015-09-07 14:01:44

标签: json parsing gson

我得到像这样的Json数据:

{
  "crowds": [
    {
      "_id": "55ed5f87cdc20e5b2d7ba546",
      "name": "The 1 crowd"
    },
    {
      "_id": "55ed6d1a6cc793110057587d",
      "name": "testCrowd"
    },
    {
      "_id": "55ed74e2d960a18c3adb3cd7",
      "name": "The crowd"
    }
  ]
}

对应Crowd类:

public class Crowd {
    private String _id;
    private String name;
}

我想使用Gson将Json数据转换为Crowd对象列表。以下方法源自官方Gson示例:

private static Type listCrowdType = new TypeToken<List<Crowd>>(){}.getType();    
public void handleJsonResponse(String jsonString) {
        JsonParser jsonParser = new JsonParser();
        JsonArray array = jsonParser.parse(jsonString).getAsJsonArray();
        List<Crowd> crowds = gson.fromJson(array.get(0), listCrowdType);
    }

在哪种情况下,Gson告诉我This is not a JSON Array. 我甚至无法计算我尝试转换jsonString并将其传递给Gson的所有不同方式,但它从不开心,给我不同的错误,如Expected BEGIN_OBJECT but was BEGIN_STRING等。 怎么办呢?

我试过的其他事情:

public void handleJsonResponse(String jsonString) {
    JsonParser jsonParser = new JsonParser();
    JsonElement jsonElement = jsonParser.parse(jsonString);
    JsonObject jsonObject = jsonElement.getAsJsonObject();

    List<Crowd> crowds = gson.fromJson(jsonObject.get("crowds"), listCrowdType);
}

错误:Expected BEGIN_OBJECT but was STRING

1 个答案:

答案 0 :(得分:0)

您可以尝试以下代码:

Gson gson = new Gson();
try {
    JSONObject jsonObject = new JSONObject(jsonString);
    if (!jsonObject.isNull("crowds")) {                    
        JSONArray jsonArray = jsonObject.getJSONArray("crowds");
        Crowd[] crowdList = gson.fromJson(jsonArray.toString(), Crowd[].class);
        List<Crowd> crowds = new ArrayList<>(Arrays.asList(crowdList));    
    }        
} catch (JSONException e) {
    e.printStackTrace();
}

希望这有帮助!