2 回答

TA貢獻1810條經(jīng)驗 獲得超4個贊
這是一個使用GSON?(谷歌的 json 庫)的工作示例:
請注意,您必須使用""引號而不是“”,因為后者在 JSON 中無效。如果需要,您可以.replaceAll(...)在輸入字符串上使用替換這些字符。
public class ReadCarFile {
? ? public static final Gson gson = new GsonBuilder().registerTypeAdapter(Car.class, new CarTypeAdapter()).create();
? ? public static void main(String[] args) {
? ? ? ? String input = "{\"car\":{\"name\":\"Toyota\",\"vin\":637834623,\"location\":”SomePlace\"}}";
? ? ? ? Car result = gson.fromJson(input, Car.class);
? ? }
? ? static class CarTypeAdapter implements JsonDeserializer<Car> {
? ? ? ? @Override
? ? ? ? public Car deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
? ? ? ? ? ? JsonObject carObject = jsonElement.getAsJsonObject().get("car").getAsJsonObject();
? ? ? ? ? ? Car car = new Car();
? ? ? ? ? ? car.name = carObject.get("name").getAsString();
? ? ? ? ? ? car.vin = carObject.get("vin").getAsInt();
? ? ? ? ? ? car.location = carObject.get("location").getAsString();
? ? ? ? ? ? return car;
? ? ? ? }
? ? }
? ? static class Car {
? ? ? ? @SerializedName("name")
? ? ? ? public String name;
? ? ? ? @SerializedName("vin")
? ? ? ? public int vin;
? ? ? ? @SerializedName("location")
? ? ? ? public String location;
? ? }
}

TA貢獻1875條經(jīng)驗 獲得超5個贊
這些數(shù)字不需要像上面提到的那樣被引用,下面是有效的 JSON。使用像這里這樣的 JSON linter將確認這一點。使用GSON或Jackson之類的包將其反序列化為您的 Java 應(yīng)用程序可以輕松使用的 Car POJO。我個人喜歡 Jackson,盡管對于簡單的使用來說它可能有點重量級。
{
? ? "car": {
? ? ? ? "name": "Toyota",
? ? ? ? "vin": 637834623,
? ? ? ? "location": "SomePlace"
? ? }
}
添加回答
舉報