0

JSON 応答文字列:

{
    "1": {
        "registered_name": "Manchester Cars",
        "search_tag": null,
        "town": "Manchester",
        "distance": "1.03782874345779",
        "capacity": 4,
        "first_address_line": null,
        "price": "165.00",
        "cost_per_person": "165.00",
        "trip_direction": 1,
        "mco_id": "826",
        "tag": ""
    },
    "2": {
        "registered_name": "Avon Cars",
        "search_tag": null,
        "town": "Solihull",
        "distance": "3.39530396461487",
        "capacity": 4,
        "first_address_line": null,
        "price": "140.82",
        "cost_per_person": "140.82",
        "trip_direction": 1,
        "mco_id": "670",
        "tag": ""
    },
    "3": {
        "registered_name": "BBS Executive",
        "search_tag": null,
        "town": "Birmingham",
        "distance": "11.7371127605438",
        "capacity": 4,
        "first_address_line": null,
        "price": "186.17",
        "cost_per_person": "186.17",
        "trip_direction": 1,
        "mco_id": "615",
        "tag": ""
    },
    "4": {
        "registered_name": "Sky Cars",
        "search_tag": null,
        "town": "Birmingham",
        "distance": "14.4878869056702",
        "capacity": 4,
        "first_address_line": null,
        "price": "179.13",
        "cost_per_person": "179.13",
        "trip_direction": 1,
        "mco_id": "822",
        "tag": ""
    },
    "": {
        "registered_name": "Eco Cars Manchester",
        "search_tag": null,
        "town": "Stockport",
        "distance": "9.5043933391571",
        "capacity": 4,
        "first_address_line": null,
        "price": "155.00",
        "cost_per_person": "155.00",
        "trip_direction": 1,
        "mco_id": "774",
        "tag": ""
    }
}

この json レスポンスを変換したいのですが、次の GSON コードを使用していますが、変換に失敗しました。

試した解決策1

Gson gson = new Gson();         
Item[] itemList = gson.fromJson(jstring, Item[].class);    
Type collectionType = new TypeToken<Collection<Item>>(){}.getType();
List<Item> enums =  gson.fromJson(jstring, collectionType);

試した解決策2

Gson gson = new Gson();         
Item[] itemList = gson.fromJson(jstring, Item[].class);

jstring は、上記の json 応答です。

失敗しました: java.lang.IllegalStateException: BEGIN_ARRAY が必要でしたが、1 行 2 列目で BEGIN_OBJECT でした

4

2 に答える 2

2

JSON レスポンスは JSON 配列ではありません。JSON オブジェクトです。それがあなたのエラーの原因です。www.json.orgを参照

于 2012-10-15T12:00:25.727 に答える
1

Genson http://code.google.com/p/genson/を試すことができます。次のコードで問題が解決するはずです。

Map<String, Item> itemsMap = new Genson().deserialize(jsonString, new GenericType<Map<String, Item>>() {});
// get all the items independently from their keys
Collection<Items> items = itemsMap.values();
于 2012-10-15T13:25:37.017 に答える