使用gson Java进行复杂的JSON反序列化

时间:2016-05-18 18:06:09

标签: java json gson json-deserialization android

如何反序列化这个复杂的JSON。 我想访问所有对象并阅读。 例如,通过索引编辑SelectionId和AdditionalPriceInfo字段。 get(0).getSelectionId() - > d51d38c9-6e51-473c-b843-f24fef632f89

{
    "Status": 0,
    "Message": "",
    "Result": {
        "HasMore": "False",
        "Itineraries": [
            {
                "SelectionId": "d51d38c9-6e51-473c-b843-f24fef632f89",
                "AdditionalPriceInfo": null,
                "Trips": [
                    {
                        "TotalTravelTime": "02:00:00"
                    }
                ]
            },
            {
                "SelectionId": "ff44d76a-a4c8-4aff-9f9d-6db4e1f3092c",
                "AdditionalPriceInfo": null,
                "Trips": [
                    {
                        "TotalTravelTime": "01:23:00"
                    }
                ]
            }
        ],
        "SearchOriginCityText": "Long Beach",
        "SearchOriginAirportCode": "LGB",
        "SearchDestinationCityText": "SFO",
        "SearchDestinationAirportCode": "SFO"
    }
}

到目前为止,我的代码用于访问我想要的所有内容:

Gson gson2 = new Gson();

AirJson airJson = gson2.fromJson(airFullResult3, AirJson.class);
Itineraries itineraries = gson2.fromJson(airFullResult3, Itineraries.class);
Result result = gson2.fromJson(airFullResult3, Result.class);

//Having null instead SFO
System.out.println(result.getSearchDestinationAirportCode());

//Having null
System.out.println(itineraries.getAdditionalPriceInfo());

当我分割我的JSON时,我可以访问我想要的值。

{
    "Itineraries": [{
        "SelectionId": "d51d38c9-6e51-473c-b843-f24fef632f89",
        "AdditionalPriceInfo": null

    }, {
        "SelectionId": "dda40b80-d8e4-4b76-9f78-83297b52afe9",
        "AdditionalPriceInfo": null
    }]

}

成功的代码和我访问值。

 JsonParser parser = new JsonParser();
 JsonObject rootObject = parser.parse(airFullResult).getAsJsonObject();
 JsonElement projectElement = rootObject.get("Itineraries");

 Type listofObject = new TypeToken<List<Itineraries>>(){}.getType();
 List<Itineraries> itiList = gson2.fromJson(projectElement, listofObject);

 //Having d51d38c9-6e51-473c-b843-f24fef632f89 as a result
 //which is great
 System.out.println(itiList.get(0).getSelectionId());

当我为第一个未分配的JSON使用相同的代码时,不起作用并将java.lang.NullPointerException作为错误

1 个答案:

答案 0 :(得分:0)

您需要使用几个代表json结构的子对象构建一个对象。以下代码有效! (用java 8和gson 2.6.2测试)

@Test
public void test() {
    Gson gson = new Gson();
    Data data = gson.fromJson(getJson(), Data.class);

    Assert.assertNotNull(data);
    Assert.assertNotNull(data.result);
    Assert.assertNotNull(data.result.itineraries);
    Assert.assertEquals(2, data.result.itineraries.length);
    Assert.assertEquals("d51d38c9-6e51-473c-b843-f24fef632f89", data.result.itineraries[0].selectionId);
    Assert.assertEquals("ff44d76a-a4c8-4aff-9f9d-6db4e1f3092c", data.result.itineraries[1].selectionId);
}

public class Data {
    @SerializedName("Status")
    int status;
    @SerializedName("Message")
    String message;
    @SerializedName("Result")
    Result result;
}

public class Result {
    @SerializedName("HasMore")
    String hasMore;
    @SerializedName("Itineraries")
    Itineraries[] itineraries;
    @SerializedName("SearchOriginCityText")
    String searchOriginCityText;
    @SerializedName("SearchOriginAirportCode")
    String searchOriginAirportCode;
    @SerializedName("SearchDestinationCityText")
    String searchDestinationCityText;
    @SerializedName("SearchDestinationAirportCode")
    String searchDestinationAirportCode;
}

public class Itineraries {
    @SerializedName("SelectionId")
    String selectionId;
    @SerializedName("AdditionalPriceInfo")
    String additionalPriceInfo;
    @SerializedName("Trips")
    Trips[] trips;
}

public class Trips {
    @SerializedName("TotalTravelTime")
    String totalTravelTime;
}

private String getJson() {
    String json = "";
    json += "{";
    json += "    \"Status\": 0,";
    json += "    \"Message\": \"\",";
    json += "    \"Result\": {";
    json += "        \"HasMore\": \"False\",";
    json += "        \"Itineraries\": [";
    json += "            {";
    json += "                \"SelectionId\": \"d51d38c9-6e51-473c-b843-f24fef632f89\",";
    json += "                \"AdditionalPriceInfo\": null,";
    json += "                \"Trips\": [";
    json += "                    {";
    json += "                        \"TotalTravelTime\": \"02:00:00\"";
    json += "                    }";
    json += "                ]";
    json += "            },";
    json += "            {";
    json += "                \"SelectionId\": \"ff44d76a-a4c8-4aff-9f9d-6db4e1f3092c\",";
    json += "                \"AdditionalPriceInfo\": null,";
    json += "                \"Trips\": [";
    json += "                    {";
    json += "                        \"TotalTravelTime\": \"01:23:00\"";
    json += "                    }";
    json += "                ]";
    json += "            }";
    json += "        ],";
    json += "        \"SearchOriginCityText\": \"Long Beach\",";
    json += "        \"SearchOriginAirportCode\": \"LGB\",";
    json += "        \"SearchDestinationCityText\": \"SFO\",";
    json += "        \"SearchDestinationAirportCode\": \"SFO\"";
    json += "    }";
    json += "}";

    return json;
}